/**
 * Created by hxpeng on 2017/3/24.
 */

'use strict';

    commonConfig.$inject = ["$ionicConfigProvider", "$urlRouterProvider", "$locationProvider", "storeProvider", "$compileProvider"];
    angular.module('App',[
        'ngAnimate',
        'angular-storage',
        'ngResource',
        'templates',
        'ui.router',
        'ionic',
        'ngTextTruncate',
        'App.common',
        'App.pages'
    ])
        .config(commonConfig)
        //.constant('API',"http://www.hxpeng.com/kinder")
        .constant('API',"http://192.168.1.204/kinder")
        .constant('Global', {
            default_avatarPath:'http://www.hxpeng.com/wechat/assets/img/default_head.png',
            path:{
                wechat_path: "http://www.hxpeng.com/wechat",
                wechat_auth_path: "https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={redirectUri}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect",
                server_wechat_test_path: "http://www.hxpeng.com/kinder/wechat/testPath",
                server_sdk_auth_path: "http://www.hxpeng.com/kinder/wechat/wechatSdkAuth"
            },
            memberType: [
                {
                    key:"teacher",
                    value:"教师"
                },
                {
                    key:"parent",
                    value:"家长"
                },
                {
                    key:"student",
                    value:"学生"
                }
            ]
        });


    /**
     * 全局插件基础设置
     * @param $ionicConfigProvider
     * @param $locationProvider
     */
    function commonConfig($ionicConfigProvider, $urlRouterProvider, $locationProvider, storeProvider,$compileProvider){




        //storage 设置为会话级别，关闭浏览器即过期
        // Store defaults to localStorage but we can set sessionStorage or cookieStorage.
        storeProvider.setStore('sessionStorage');
        //其中 weixin 是微信安卓版的 localId 的形式，wxlocalresource 是 iOS 版本的 localId 形式
        $compileProvider.imgSrcSanitizationWhitelist(/^\s*(http|https|data|weixin|wxLocalresource|wxlocalresource):/);

        //ionic 不缓存页面
        //$ionicConfigProvider.views.maxCache(0);
        //$ionicConfigProvider.views.transition('none');
        //$ionicConfigProvider.platform.ios.views.transition('ios');
        //$ionicConfigProvider.platform.android.views.transition('android');
        $ionicConfigProvider.platform.ios.navBar.alignTitle('center');
        $ionicConfigProvider.platform.android.navBar.alignTitle('center');
        $ionicConfigProvider.platform.ios.backButton.previousTitleText('').icon('ion-ios-arrow-thin-left');
        $ionicConfigProvider.platform.android.backButton.previousTitleText('').icon('ion-android-arrow-back');

        //取消路径中的#
        //$locationProvider.html5Mode(true);
        //$urlRouterProvider.otherwise("/member/bind");
    };






/**
 * Created by hxpeng on 2017/3/24.
 */

(function () {
    'use strict';
    angular.module('App.common', [

    ]);

})();
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 - <Ali Ok> - <Collin Donahue-Oponski>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

// ------ ion-affix ---------
// version 1.0.2-SNAPSHOT
// date 2015-05-19
// ion-affix is a lightweight Angular directive for Ionic framework to have sticky affix elements.
// see project page : http://www.aliok.com.tr/projects/2015-04-17-ion-affix.html


angular.module('ion-affix', ['ionic'])
    .directive('ionAffix', ['$ionicPosition', '$compile', function ($ionicPosition, $compile) {

        // keeping the Ionic specific stuff separated so that they can be changed and used within an other context

        // see https://api.jquery.com/closest/ and http://ionicframework.com/docs/api/utility/ionic.DomUtil/
        function getParentWithClass(elementSelector, parentClass) {
            return angular.element(ionic.DomUtil.getParentWithClass(elementSelector[0], parentClass));
        }

        // see http://underscorejs.org/#throttle
        function throttle(theFunction) {
            return ionic.Utils.throttle(theFunction);
        }

        // see http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
        // see http://ionicframework.com/docs/api/utility/ionic.DomUtil/
        function requestAnimationFrame(callback) {
            return ionic.requestAnimationFrame(callback);
        }

        // see https://api.jquery.com/offset/
        // see http://ionicframework.com/docs/api/service/$ionicPosition/
        function offset(elementSelector) {
            return $ionicPosition.offset(elementSelector);
        }

        // see https://api.jquery.com/position/
        // see http://ionicframework.com/docs/api/service/$ionicPosition/
        function position(elementSelector) {
            return $ionicPosition.position(elementSelector);
        }

        function applyTransform(element, transformString) {
            // do not apply the transformation if it is already applied
            if (element.style[ionic.CSS.TRANSFORM] == transformString) {
            }
            else {
                element.style[ionic.CSS.TRANSFORM] = transformString;
            }
        }

        function translateUp(element, dy, executeImmediately) {
            var translateDyPixelsUp = dy == 0 ? 'translate3d(0px, 0px, 0px)' : 'translate3d(0px, -' + dy + 'px, 0px)';
            // if immediate execution is requested, then just execute immediately
            // if not, execute in the animation frame.
            if (executeImmediately) {
                applyTransform(element, translateDyPixelsUp);
            }
            else {
                // see http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
                // see http://ionicframework.com/docs/api/utility/ionic.DomUtil/
                requestAnimationFrame(function () {
                    applyTransform(element, translateDyPixelsUp);
                });
            }
        }

        var CALCULATION_THROTTLE_MS = 500;

        return {
            // only allow adding this directive to elements as an attribute
            restrict: 'A',
            // we need $ionicScroll for adding the clone of affix element to the scroll container
            // $ionicScroll.element gives us that
            require: '^$ionicScroll',
            link: function ($scope, $element, $attr, $ionicScroll) {
                // get the affix's container. element will be affix for that container.
                // affix's container will be matched by "affix-within-parent-with-class" attribute.
                // if it is not provided, parent element will be assumed as the container
                var $container;
                if ($attr.affixWithinParentWithClass) {
                    $container = getParentWithClass($element, $attr.affixWithinParentWithClass);
                    if (!$container) {
                        $container = $element.parent();
                    }
                }
                else {
                    $container = $element.parent();
                }

                var scrollMin = 0;
                var scrollMax = 0;
                var scrollTransition = 0;
                // calculate the scroll limits for the affix element and the affix's container
                var calculateScrollLimits = function (scrollTop) {
                    var containerPosition = position($container);
                    var elementOffset = offset($element);

                    var containerTop = containerPosition.top;
                    var containerHeight = containerPosition.height;

                    var affixHeight = elementOffset.height;

                    scrollMin = scrollTop + containerTop;
                    scrollMax = scrollMin + containerHeight;
                    scrollTransition = scrollMax - affixHeight;
                };
                // throttled version of the same calculation
                var throttledCalculateScrollLimits = throttle(
                    calculateScrollLimits,
                    CALCULATION_THROTTLE_MS,
                    {trailing: false}
                );

                var affixClone = null;

                // creates the affix clone and adds it to DOM. by default it is put to top
                var createAffixClone = function () {
                    var clone = $element.clone().css({
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        right: 0
                    });

                    // if directive is given an additional CSS class to apply to the clone, then apply it
                    if ($attr.affixClass) {
                        clone.addClass($attr.affixClass);
                    }

                    // remove the directive matching attribute from the clone, so that an affix is not created for the clone as well.
                    clone.removeAttr('ion-affix').removeAttr('data-ion-affix').removeAttr('x-ion-affix');

                    angular.element($ionicScroll.element).append(clone);

                    // compile the clone so that anything in it is in Angular lifecycle.
                    $compile(clone)($scope);

                    return clone;
                };

                // removes the affix clone from DOM. also deletes the reference to it in the memory.
                var removeAffixClone = function () {
                    if (affixClone)
                        affixClone.remove();
                    affixClone = null;
                };

                $scope.$on("$destroy", function () {
                    // 2 important things on destroy:
                    // remove the clone
                    // unbind the scroll listener
                    // see https://github.com/aliok/ion-affix/issues/1
                    removeAffixClone();
                    angular.element($ionicScroll.element).off('scroll');
                });


                angular.element($ionicScroll.element).on('scroll', function (event) {
                    var scrollTop = (event.detail || event.originalEvent && event.originalEvent.detail).scrollTop;
                    // when scroll to top, we should always execute the immediate calculation.
                    // this is because of some weird problem which is hard to describe.
                    // if you want to experiment, always use the throttled one and just click on the page
                    // you will see all affix elements stacked on top
                    if (scrollTop == 0) {
                        calculateScrollLimits(scrollTop);
                    }
                    else {
                        throttledCalculateScrollLimits(scrollTop);
                    }

                    // when we scrolled to the container, create the clone of element and place it on top
                    if (scrollTop >= scrollMin && scrollTop <= scrollMax) {

                        // we need to track if we created the clone just now
                        // that is important since normally we apply the transforms in the animation frame
                        // but, we need to apply the transform immediately when we add the element for the first time. otherwise it is too late!
                        var cloneCreatedJustNow = false;
                        if (!affixClone) {
                            affixClone = createAffixClone();
                            cloneCreatedJustNow = true;
                        }

                        // if we're reaching towards the end of the container, apply some nice translation to move up/down the clone
                        // but if we're reached already to the container and we're far away than the end, move clone to top
                        if (scrollTop > scrollTransition) {
                            translateUp(affixClone[0], Math.floor(scrollTop - scrollTransition), cloneCreatedJustNow);
                        } else {
                            translateUp(affixClone[0], 0, cloneCreatedJustNow);
                        }
                    } else {
                        removeAffixClone();
                    }
                });
            }
        }
    }]);
(function(){
  'use strict';

  angular
    .module('ion-gallery', ['templates'])
    .directive('ionGallery',ionGallery);

  ionGallery.$inject = ['$ionicPlatform','ionGalleryData','ionGalleryConfig'];

  function ionGallery($ionicPlatform,ionGalleryData,ionGalleryConfig) {
    controller.$inject = ["$scope"];
    return {
      restrict: 'AE',
      scope:{
        ionGalleryItems: '=ionGalleryItems',
        ionGalleryRow: '=ionGalleryRow'
      },
      controller: controller,
      link:link,
      replace:true,
      templateUrl:'gallery.html'
    };

    function controller($scope){
      ionGalleryData.setGallery($scope.ionGalleryItems);
      ionGalleryData.setRowSize(parseInt($scope.ionGalleryRow) || ionGalleryConfig.row_size);
      $scope.actionLabel = ionGalleryConfig.action_label;

      var _drawGallery = function(){
        $scope.items = ionGalleryData.buildGallery();
        $scope.responsiveGrid = ionGalleryData.getGridSize();
      };

      _drawGallery();

      (function () {
        $scope.$watch(function () {
          return $scope.ionGalleryItems.length;
        }, function (newVal, oldVal) {
          if(newVal !== oldVal){
            ionGalleryData.setGallery($scope.ionGalleryItems);
            _drawGallery();

          }
        });
      }());

    }

    function link(scope,element,attrs){
      scope.ionSliderToggle = attrs.ionGalleryToggle === 'false' ? false : ionGalleryConfig.toggle;
    }
  }
})();

(function(){
  'use strict';

  angular
    .module('ion-gallery')
    .provider('ionGalleryConfig',ionGalleryConfig);

  ionGalleryConfig.$inject = [];

  function ionGalleryConfig(){
    this.config = {
      action_label: 'Done',
      toggle: true,
      row_size: 3
    };

    this.$get = function() {
        return this.config;
    };

    this.setGalleryConfig = function(config) {
        angular.extend(this.config, this.config, config);
    };
  }

})();
(function(){
  'use strict';
  
  angular
    .module('ion-gallery')
    .service('ionGalleryData',ionGalleryData);
  
  ionGalleryData.$inject = ['ionGalleryConfig'];
  
  function ionGalleryData(ionGalleryConfig) {
    
    var galleryLength;
    var gallery;
    var _this = this;
    
    _this.setGalleryLength = function(length){
      galleryLength = length;
    };
    
    this.getGalleryLength = function(){
      return galleryLength;
    };
    
    this.setRowSize = function(size){
      var length = _this.getGalleryLength;
      var rowSize;
      
      if(isNaN(size) === true){
        rowSize = 3;
      }
      else if(size > length){
        rowSize = length;
      }
      else if(size <= 0){
        rowSize = 1;
      }
      else{
        rowSize = size;
      }
      
      ionGalleryConfig.row_size = rowSize;
      
    };
    
    this.getRowSize = function(){
      return ionGalleryConfig.row_size;
    };
    
    this.setGallery = function(items){
      gallery = items;
      _this.setGalleryLength(items.length);
    };
    
    this.getGallery = function(){
      return gallery;
    };
    
    this.buildGallery = function(){
      var items = this.getGallery();
      var rowSize = this.getRowSize();
      var _gallery = [];
      var row = -1;
      var col = 0;
            
      for(var i=0;i<items.length;i++){
        
        if(i % rowSize === 0){
          row++;
          _gallery[row] = [];
          col = 0;
        }
        
        if(!items[i].hasOwnProperty('sub')){
          items[i].sub = '';
        }
        
        items[i].position = i;
        
        _gallery[row][col] = items[i];
        col++;
      }
      
      return _gallery;
    };
  
    this.getGridSize = function(){
      return parseInt((1/this.getRowSize())* 100);
    };
    
  }
})();
(function(){
  'use strict';

  angular
    .module('ion-gallery')
    .directive('ionImageScale',ionImageScale);

  ionImageScale.$inject = [];

  function ionImageScale(){
    
    return {
      restrict: 'A',
      link : link
    };

    function link(scope, element, attrs) {
      
      var scaleImage = function(context,value) {
        if(value>0){
          if(context.naturalHeight > context.naturalWidth){
            element.attr('width','100%');
          }
          else{
            element.attr('height',element.parent()[0].offsetHeight+'px');
          }
        } 
      };
      
      element.bind("load" , function(e){
        if(element.parent()[0].offsetHeight > 0){
          scaleImage(this,element.parent()[0].offsetHeight);
        }
        else{
          var _this = this;
          scope.$watch(function(){
            return element.parent()[0].offsetHeight;
          },function(newValue){
            scaleImage(_this,newValue);
          });
        }
      });
    }
  }
})();
(function(){
  'use strict';

  angular
    .module('ion-gallery')
    .directive('ionRowHeight',ionRowHeight);

  ionRowHeight.$inject = [];

  function ionRowHeight(){
    
    return {
      restrict: 'A',
      link : link
    };

    function link(scope, element, attrs) {
            
      scope.$watch( 
        function(){
          return element[0].offsetWidth;
        },
        function(newValue){
          if(newValue > 0){
            element.css('height',newValue * parseInt(scope.$parent.responsiveGrid)/100 + 'px');
          }
        });
    }
  }
})();
(function(){
  'use strict';

  angular
    .module('ion-gallery')
    .directive('ionSlideAction',ionSlideAction);

  ionSlideAction.$inject = ['$ionicGesture','$timeout'];

  function ionSlideAction($ionicGesture, $timeout){
    
    return {
      restrict: 'A',
      link : link
    };

    function link(scope, element, attrs) {
      
      var isDoubleTapAction = false;
      
      var pinchZoom = function pinchZoom(){
        if(getZoomLevel() > 1){
          scope.$emit('ZoomStarted');
        }
        else{
          scope.$emit('ZoomOriginal');
        }
      };
      
      var imageDoubleTapGesture = function imageDoubleTapGesture(event) {
        
        isDoubleTapAction = true;
                
        $timeout(function(){
          isDoubleTapAction = false;
          scope.$emit('DoubleTapEvent',{ 'x': event.gesture.touches[0].pageX, 'y': event.gesture.touches[0].pageY});
        },200);
      };

      var imageTapGesture = function imageTapGesture(event) {
        
        if(isDoubleTapAction === true){
          return;
        }
        else{
          $timeout(function(){
            if(isDoubleTapAction === true){
              return;
            }
            else{
              scope.$emit('TapEvent');
            }
          },200);
        }
      };
      
      var getZoomLevel = function() {
        var match = element[0].getElementsByClassName('scroll')[0].style.webkitTransform.match(/scale\(([^)]+)\)/);
        
        return parseFloat(match[1]);
      };
      
      var pinchEvent = $ionicGesture.on('pinch',pinchZoom,element);
      var doubleTapEvent = $ionicGesture.on('doubletap', function(e){imageDoubleTapGesture(e);}, element);
      var tapEvent = $ionicGesture.on('tap', imageTapGesture, element);
      
      scope.$on('$destroy', function() {
        $ionicGesture.off(doubleTapEvent, 'doubletap', imageDoubleTapGesture);
        $ionicGesture.off(tapEvent, 'tap', imageTapGesture);
        $ionicGesture.off(pinchEvent, 'pinch', pinchZoom);
      });
    }
  }
})();
(function(){
  'use strict';

  angular
    .module('ion-gallery')
    .directive('ionSlider',ionSlider);

  ionSlider.$inject = ['$ionicModal','ionGalleryData','$ionicPlatform','$timeout','$ionicScrollDelegate'];

  function ionSlider($ionicModal,ionGalleryData,$ionicPlatform,$timeout,$ionicScrollDelegate){
    
    controller.$inject = ["$scope"];
    return {
      restrict: 'A',
      controller: controller,
      link : link
    };
    
    function controller($scope){
      var lastSlideIndex;
      var currentImage;
      
      var rowSize = ionGalleryData.getRowSize();
      var zoomStart = false;
          
      $scope.selectedSlide = 1;
      $scope.hideAll = false;
      
      $scope.showImage = function(index) {
        $scope.slides = [];
        
        currentImage = index;
        
        var galleryLength = ionGalleryData.getGalleryLength();
        var previndex = index - 1 < 0 ? galleryLength - 1 : index - 1;
        var nextindex = index + 1 >= galleryLength ? 0 : index + 1;

        $scope.slides[0] = $scope.ionGalleryItems[previndex];
        $scope.slides[1] = $scope.ionGalleryItems[index];
        $scope.slides[2] = $scope.ionGalleryItems[nextindex];
        
        console.log( 'loadSingles: ' + previndex + ' ' + index + ' ' + nextindex);

        lastSlideIndex = 1;
        $scope.loadModal();
      };

      $scope.compartirImg = function(){
            var src = $scope.ionGalleryItems[currentImage].src;
            alert(src);
      };
      $scope.slideChanged = function(currentSlideIndex) {
        
        if(currentSlideIndex === lastSlideIndex){
          return;
        }

        var slideToLoad = $scope.slides.length - lastSlideIndex - currentSlideIndex;
        var galleryLength = ionGalleryData.getGalleryLength();
        var imageToLoad;
        var slidePosition = lastSlideIndex + '>' + currentSlideIndex;
        
        console.log( 'loadSingles: ' + slidePosition);
        
        if(slidePosition === '0>1' || slidePosition === '1>2' || slidePosition === '2>0'){
          currentImage++;
          imageToLoad = currentImage + 1;
        }
        else if(slidePosition === '0>2' || slidePosition === '1>0' || slidePosition === '2>1'){
          currentImage--;
          imageToLoad = currentImage - 1;
        }

        if( currentImage < 0 ){
          currentImage = galleryLength - 1;
        }

        if( currentImage >= galleryLength ){
          currentImage = 0;
        }

        if( imageToLoad < 0 ){
          imageToLoad = galleryLength + imageToLoad;
        }

        if( imageToLoad >= galleryLength ){
          imageToLoad = imageToLoad - galleryLength;
        }

        //Clear zoom
        $ionicScrollDelegate.$getByHandle('slide-' + slideToLoad).zoomTo(1);
        
        $scope.slides[slideToLoad] = $scope.ionGalleryItems[imageToLoad];
        
        lastSlideIndex = currentSlideIndex;
      };
            
      $scope.$on('ZoomStarted', function(e){
        $timeout(function () {
          zoomStart = true;
          $scope.hideAll = true;
        });
        
      });
      
      $scope.$on('ZoomOriginal', function(e){
        $timeout(function () {
          _isOriginalSize();
        },300);
        
      });
      
      $scope.$on('TapEvent', function(e){
        $timeout(function () {
          _onTap();
        });
        
      });
      
      $scope.$on('DoubleTapEvent', function(event,position){
        $timeout(function () {
          _onDoubleTap(position);
        });
        
      });
      
      var _onTap = function _onTap(){
        
        if(zoomStart === true){
          $ionicScrollDelegate.$getByHandle('slide-'+lastSlideIndex).zoomTo(1,true);
          
          $timeout(function () {
            _isOriginalSize();
          },300);
          
          return;
        }
        
        if(($scope.hasOwnProperty('ionSliderToggle') && $scope.ionSliderToggle === false && $scope.hideAll === false) || zoomStart === true){
          return;
        }
        
        $scope.hideAll = !$scope.hideAll;
      };
      
      var _onDoubleTap = function _onDoubleTap(position){
        if(zoomStart === false){
          $ionicScrollDelegate.$getByHandle('slide-'+lastSlideIndex).zoomTo(3,true,position.x,position.y);
          zoomStart = true;
          $scope.hideAll = true;
        }
        else{
          _onTap();
        }
      };
      
      function _isOriginalSize(){
        zoomStart = false;
        _onTap();
      }
      
    }

    function link(scope, element, attrs) {
      var _modal;

      scope.loadModal = function(){
        $ionicModal.fromTemplateUrl('slider.html', {
          scope: scope,
          animation: 'fade-in'
        }).then(function(modal) {
          _modal = modal;
          scope.openModal();
        });
      };

      scope.openModal = function() {
        _modal.show();
      };

      scope.closeModal = function() {
        _modal.hide();
      };

      scope.$on('$destroy', function() {
        try{
          _modal.remove();
        } catch(err) {
          console.log(err.message);
        }
      });
    }
  }
})();
angular.module("templates", []).run(["$templateCache", function($templateCache) {$templateCache.put("gallery.html","<div class=\"gallery-view\">\n  <div class=\"row\" ng-repeat=\"item in items track by $index\" ion-row-height>\n    <div ng-repeat=\"photo in item track by $index\"\n         class=\"col col-{{responsiveGrid}} image-container\">\n      \n      <img ion-image-scale\n           ng-src=\"{{photo.src}}\"\n           ng-click=\"showImage({{photo.position}})\">\n      \n    </div>\n  </div>\n  <div ion-slider></div>\n</div>");
$templateCache.put("slider.html","<ion-modal-view class=\"imageView\">\n  <ion-header-bar class=\"headerView bar-positive\" ng-show=\"!hideAll\">\n  <button class=\"button button-clear button-light icon ion-share\" ng-click=\"compartirImg()\"></button>\n <div class=\"h1 title\"></div> <button class=\"button button-clear button-light icon ion-close-circled close-btn\" ng-click=\"closeModal()\"></button>\n  </ion-header-bar>\n\n  <ion-content class=\"has-no-header\" scroll=\"false\">\n    <ion-slide-box does-continue=\"true\" active-slide=\"selectedSlide\" show-pager=\"false\" class=\"listContainer\" on-slide-changed=\"slideChanged($index)\">\n      <ion-slide ng-repeat=\"single in slides track by $index\">\n        <ion-scroll direction=\"xy\"\n                    locking=\"false\"\n                    zooming=\"true\"\n                    min-zoom=\"1\"\n                    scrollbar-x=\"false\"\n                    scrollbar-y=\"false\"\n                    ion-slide-action\n                    delegate-handle=\"slide-{{$index}}\"\n                    >\n        <div class=\"item item-image gallery-slide-view\">\n          <img ng-src=\"{{single.src}}\">\n        </div>\n        <div ng-if=\"single.sub.length > 0\" class=\"image-subtitle\" ng-show=\"!hideAll\">\n            <span ng-bind-html=\'single.sub\'></span>\n        </div>\n        </ion-scroll>\n      </ion-slide>\n    </ion-slide-box>\n  </ion-content>\n</ion-modal-view>\n");}]);
angular.module('jett.ionic.filter.bar', ['ionic']);
(function (angular) {
  'use strict';

  angular.module('jett.ionic.filter.bar')
    .directive('ionFilterBar', [
      '$document',
      '$timeout',
      '$ionicGesture',
      '$ionicPlatform',
      function ($document, $timeout, $ionicGesture, $ionicPlatform) {
        var filterBarTemplate;

        //create platform specific filterBar template using filterConfig items
        if ($ionicPlatform.is('android')) {
          filterBarTemplate =
            '<div class="filter-bar-wrapper filter-bar-{{::config.theme}} filter-bar-transition-{{::config.transition}}">' +
              '<div class="bar bar-header bar-{{::config.theme}} item-input-inset">' +
                '<button class="filter-bar-cancel button button-icon icon {{::config.back}}"></button>' +
                '<label class="item-input-wrapper">' +
                  '<input type="search" class="filter-bar-search" ng-model="filterText" placeholder="{{::config.placeholder}}" />' +
                  '<button style="display:none;" class="filter-bar-clear button button-icon icon {{::config.clear}}"></button>' +
                '</label>' +
              '</div>' +
            '</div>';
        } else {
          filterBarTemplate =
            '<div class="filter-bar-wrapper filter-bar-{{::config.theme}} filter-bar-transition-{{::config.transition}}">' +
              '<div class="bar bar-header bar-{{::config.theme}} item-input-inset">' +
                '<label class="item-input-wrapper">' +
                  '<i class="icon {{::config.search}} placeholder-icon"></i>' +
                  '<input type="search" class="filter-bar-search" ng-model="filterText" placeholder="{{::config.placeholder}}"/>' +
                  '<button style="display:none;" class="filter-bar-clear button button-icon icon {{::config.clear}}"></button>' +
                '</label>' +
                '<button class="filter-bar-cancel button button-clear" ng-bind-html="::cancelText"></button>' +
              '</div>' +
            '</div>';
        }

        return {
          restrict: 'E',
          scope: true,
          link: function ($scope, $element) {
            var clearEl = angular.element($element[0].querySelector('.filter-bar-clear'));
            var cancelEl = angular.element($element[0].querySelector('.filter-bar-cancel'));
            var inputEl = $element.find('input');
            var filterTextTimeout;
            var swipeGesture;
            var backdrop;
            var backdropClick;
            var filterWatch;

            $scope.filterText = '';

            // Action when filter bar is cancelled via backdrop click/swipe or cancel/back buton click.
            // Invokes cancel function defined in filterBar service
            var cancelFilterBar = function () {
              $scope.cancelFilterBar();
            };

            cancelEl.bind('click', cancelFilterBar);

            // If backdrop is enabled, create and append it to filter, then add click/swipe listeners to cancel filter
            if ($scope.config.backdrop) {
              backdrop = angular.element('<div class="filter-bar-backdrop"></div>');
              $element.append(backdrop);

              backdropClick = function(e) {
                if (e.target == backdrop[0]) {
                  cancelFilterBar();
                }
              };

              backdrop.bind('click', backdropClick);
              swipeGesture = $ionicGesture.on('swipe', backdropClick, backdrop);
            }

            // No need to hide/show clear button via ng-show since we can easily do this with jqLite.  inline is fastest
            var showClearButton = function () {
              if(clearEl.css('display') === 'none') {
                clearEl.css('display', 'block');
              }
            };
            var hideClearButton = function () {
              if(clearEl.css('display') === 'block') {
                clearEl.css('display', 'none');
              }
            };

            // When clear button is clicked, clear filterText, hide clear button, show backdrop, and focus the input
            var clearClick = function () {
              $timeout(function () {
                $scope.filterText = '';
                hideClearButton();
                ionic.requestAnimationFrame(function () {
                  $scope.showBackdrop();
                  $scope.scrollItemsTop();
                  $scope.focusInput();
                });
              });
            };

            // Since we are wrapping with label, need to bind touchstart rather than click.
            // Even if we use div instead of label need to bind touchstart.  Click isn't allowing input to regain focus quickly
            clearEl.bind('touchstart mousedown', clearClick);

            // Bind touchstart so we can regain focus of input even while scrolling
            inputEl.bind('touchstart mousedown', function () {
              $scope.scrollItemsTop();
              $scope.focusInput();
            });

            // When a non escape key is pressed, show/hide backdrop/clear button based on filterText length
            var keyUp = function(e) {
              if (e.which == 27) {
                cancelFilterBar();
              } else if ($scope.filterText && $scope.filterText.length) {
                showClearButton();
                $scope.hideBackdrop();
              } else {
                hideClearButton();
                $scope.showBackdrop();
              }
            };

            $document.bind('keyup', keyUp);

            // Calls the services filterItems function with the filterText to filter items
            var filterItems = function () {
              $scope.filterItems($scope.filterText);
            };

            // Clean up when scope is destroyed
            $scope.$on('$destroy', function() {
              $element.remove();
              $document.unbind('keyup', keyUp);
              if (backdrop) {
                $ionicGesture.off(swipeGesture, 'swipe', backdropClick);
              }
              filterWatch();
            });

            // Watch for changes on filterText and call filterItems when filterText has changed.
            // If debounce is enabled, filter items by the specified or default delay.
            // Prefer timeout debounce over ng-model-options so if filterText is cleared, initial items show up right away with no delay
            filterWatch = $scope.$watch('filterText', function (newFilterText, oldFilterText) {
              var delay;

              if (filterTextTimeout) {
                $timeout.cancel(filterTextTimeout);
              }

              if (newFilterText !== oldFilterText) {
                delay = (newFilterText.length && $scope.debounce) ? $scope.delay : 0;
                filterTextTimeout = $timeout(filterItems, delay, false);
              }
            });
          },
          template: filterBarTemplate
        };
      }]);

})(angular);

/* global angular */
/**
 * This copies the functionality of the ionicConfig provider to allow for platform specific configuration
 */
(function (angular) {
  'use strict';

  angular.module('jett.ionic.filter.bar')
    .provider('$ionicFilterBarConfig', function () {

      var provider = this;
      provider.platform = {};
      var PLATFORM = 'platform';

      var configProperties = {
        theme: PLATFORM,
        clear: PLATFORM,
        search: PLATFORM,
        backdrop: PLATFORM,
        transition: PLATFORM,
        platform: {},
        placeholder: PLATFORM
      };

      createConfig(configProperties, provider, '');

      // Default
      // -------------------------
      setPlatformConfig('default', {
        clear: 'ion-ios-close',
        search: 'ion-ios-search-strong',
        backdrop: true,
        transition: 'vertical',
        placeholder: 'Search'
      });

      // iOS (it is the default already)
      // -------------------------
      setPlatformConfig('ios', {});

      // Android
      // -------------------------
      setPlatformConfig('android', {
        clear: 'ion-android-close',
        search: false,
        backdrop: false,
        transition: 'horizontal'
      });

      provider.setPlatformConfig = setPlatformConfig;

      // private: used to set platform configs
      function setPlatformConfig(platformName, platformConfigs) {
        configProperties.platform[platformName] = platformConfigs;
        provider.platform[platformName] = {};

        addConfig(configProperties, configProperties.platform[platformName]);

        createConfig(configProperties.platform[platformName], provider.platform[platformName], '');
      }

      // private: used to recursively add new platform configs
      function addConfig(configObj, platformObj) {
        for (var n in configObj) {
          if (n != PLATFORM && configObj.hasOwnProperty(n)) {
            if (angular.isObject(configObj[n])) {
              if (!angular.isDefined(platformObj[n])) {
                platformObj[n] = {};
              }
              addConfig(configObj[n], platformObj[n]);

            } else if (!angular.isDefined(platformObj[n])) {
              platformObj[n] = null;
            }
          }
        }
      }

      // private: create methods for each config to get/set
      function createConfig(configObj, providerObj, platformPath) {
        angular.forEach(configObj, function(value, namespace) {

          if (angular.isObject(configObj[namespace])) {
            // recursively drill down the config object so we can create a method for each one
            providerObj[namespace] = {};
            createConfig(configObj[namespace], providerObj[namespace], platformPath + '.' + namespace);

          } else {
            // create a method for the provider/config methods that will be exposed
            providerObj[namespace] = function(newValue) {
              if (arguments.length) {
                configObj[namespace] = newValue;
                return providerObj;
              }
              if (configObj[namespace] == PLATFORM) {
                // if the config is set to 'platform', then get this config's platform value
                var platformConfig = stringObj(configProperties.platform, ionic.Platform.platform() + platformPath + '.' + namespace);
                if (platformConfig || platformConfig === false) {
                  return platformConfig;
                }
                // didnt find a specific platform config, now try the default
                return stringObj(configProperties.platform, 'default' + platformPath + '.' + namespace);
              }
              return configObj[namespace];
            };
          }

        });
      }

      //splits a string by dot operator and accesses the end var.  For example in a.b.c,
      function stringObj(obj, str) {
        str = str.split(".");
        for (var i = 0; i < str.length; i++) {
          if (obj && angular.isDefined(obj[str[i]])) {
            obj = obj[str[i]];
          } else {
            return null;
          }
        }
        return obj;
      }

      provider.$get = function() {
        return provider;
      };

    });

})(angular);

/* global angular,ionic */
/**
 * @ngdoc service
 * @name $ionicFilterBar
 * @module ionic
 * @description The Filter Bar is an animated bar that allows a user to search or filter an array of items.
 */
(function (angular, ionic) {
  'use strict';

  var getNavBarTheme = function ($navBar) {
    var themes = ['light', 'stable', 'positive', 'calm', 'balanced', 'energized', 'assertive', 'royal', 'dark'];
    var classList = $navBar && $navBar.classList;

    if (!classList) {
      return;
    }

    for (var i = 0; i < themes.length; i++) {
      if (classList.contains('bar-' + themes[i])) {
        return themes[i];
      }
    }
  };

  angular.module('jett.ionic.filter.bar')
    .factory('$ionicFilterBar', [
      '$document',
      '$rootScope',
      '$compile',
      '$timeout',
      '$filter',
      '$ionicPlatform',
      '$ionicFilterBarConfig',
      '$ionicConfig',
      '$ionicScrollDelegate',
      function ($document, $rootScope, $compile, $timeout, $filter, $ionicPlatform, $ionicFilterBarConfig, $ionicConfig, $ionicScrollDelegate) {
        var isShown = false;
        var $body = angular.element($document[0].body);
        var templateConfig = {
          theme: $ionicFilterBarConfig.theme(),
          transition: $ionicFilterBarConfig.transition(),
          back: $ionicConfig.backButton.icon(),
          clear: $ionicFilterBarConfig.clear(),
          search: $ionicFilterBarConfig.search(),
          backdrop: $ionicFilterBarConfig.backdrop(),
          placeholder: $ionicFilterBarConfig.placeholder()
        };

        /**
         * @ngdoc method
         * @name $ionicFilterBar#show
         * @description
         * Load and return a new filter bar.
         *
         * A new isolated scope will be created for the filter bar and the new filter bar will be appended to the
         * body, covering the header bar.
         *
         * @returns {function} `hideFilterBar` A function which, when called, hides & cancels the filter bar.
         */
        function filterBar (opts) {
          //if filterBar is already shown return
          if (isShown) {
            return;
          }

          isShown = true;
          opts = opts || {};

          var scope = $rootScope.$new(true);
          var backdropShown = false;
          var isKeyboardShown = false;

          //if container option is set, determine the container element by querying for the container class
          if (opts.container) {
            opts.container = angular.element($body[0].querySelector(opts.container));
          }

          //extend scope defaults with supplied options
          angular.extend(scope, {
            config: templateConfig,
            $deregisterBackButton: angular.noop,
            update: angular.noop,
            cancel: angular.noop,
            done: angular.noop,
            scrollDelegate: $ionicScrollDelegate,
            filter: $filter('filter'),
            filterProperties: null,
            expression: null,
            comparator: null,
            debounce: true,
            delay: 300,
            cancelText: 'Cerrar',
            cancelOnStateChange: true,
            container: $body
          }, opts);

          //if no custom theme was configured, get theme of containers bar-header
          if (!scope.config.theme) {
            scope.config.theme = getNavBarTheme(scope.container[0].querySelector('.bar.bar-header'));
          }

          // Compile the template
          var element = scope.element = $compile('<ion-filter-bar class="filter-bar"></ion-filter-bar>')(scope);

          // Grab required jQLite elements
          var filterWrapperEl = element.children().eq(0);
          var input = filterWrapperEl.find('input')[0];
          var backdropEl = element.children().eq(1);

          //get scrollView
          var scrollView = scope.scrollDelegate.getScrollView();
          var canScroll = !!scrollView;

          //get the scroll container if scrolling is available
          var $scrollContainer = canScroll ? angular.element(scrollView.__container) : null;

          var stateChangeListenDone = scope.cancelOnStateChange ?
            $rootScope.$on('$stateChangeSuccess', function() { scope.cancelFilterBar(); }) :
            angular.noop;

          // Focus the input which will show the keyboard.
          var showKeyboard = function () {
            if (!isKeyboardShown) {
              isKeyboardShown = true;
              input && input.focus();
            }
          };

          // Blur the input which will hide the keyboard.
          // Even if we need to bring in ionic.keyboard in the future, blur is preferred for iOS so keyboard animates out.
          var hideKeyboard = function () {
            if (isKeyboardShown) {
              isKeyboardShown = false;
              input && input.blur();
            }
          };

          // When the filtered list is scrolled, we want to hide the keyboard as long as it's not already hidden
          var handleScroll = function () {
            if (scrollView.__scrollTop > 0) {
              hideKeyboard();
            }
          };

          // Scrolls the list of items to the top via the scroll delegate
          scope.scrollItemsTop = function () {
            canScroll && scope.scrollDelegate.scrollTop && scope.scrollDelegate.scrollTop();
          };

          // Set isKeyboardShown to force showing keyboard on search focus.
          scope.focusInput = function () {
            isKeyboardShown = false;
            showKeyboard();
          };

          // Hide the filterBar backdrop if in the DOM and not already hidden.
          scope.hideBackdrop = function () {
            if (backdropEl.length && backdropShown) {
              backdropShown = false;
              backdropEl.removeClass('active').css('display', 'none');
            }
          };

          // Show the filterBar backdrop if in the DOM and not already shown.
          scope.showBackdrop = function () {
            if (backdropEl.length && !backdropShown) {
              backdropShown = true;
              backdropEl.css('display', 'block').addClass('active');
            }
          };

          // Filters the supplied list of items via the supplied filterText.
          // How items are filtered depends on the supplied filter object, and expression
          // Filtered items will be sent to update
          scope.filterItems = function(filterText) {
            var filterExp, filteredItems;

            // pass back original list if filterText is empty.
            // Otherwise filter by expression, supplied properties, or filterText.
            if (!filterText.length) {
              filteredItems = scope.items;
            } else {
              if (scope.expression) {
                filterExp = scope.expression;
              } else if (angular.isArray(scope.filterProperties)) {
                filterExp = {};
                angular.forEach(scope.filterProperties, function (property) {
                  filterExp[property] = filterText;
                });
              } else if (scope.filterProperties) {
                filterExp = {};
                filterExp[scope.filterProperties] = filterText;
              } else {
                filterExp = filterText;
              }

              filteredItems = scope.filter(scope.items, filterExp, scope.comparator);
            }

            $timeout(function() {
              scope.update(filteredItems, filterText);
              scope.scrollItemsTop();
            });
          };

          // registerBackButtonAction returns a callback to deregister the action
          scope.$deregisterBackButton = $ionicPlatform.registerBackButtonAction(
            function() {
              $timeout(scope.cancelFilterBar);
            }, 300
          );

          // Removes the filterBar from the body and cleans up vars/events.  Once the backdrop is hidden we can invoke done
          scope.removeFilterBar = function(done) {
            if (scope.removed) return;

            scope.removed = true;

            //animate the filterBar out, hide keyboard and backdrop
            ionic.requestAnimationFrame(function () {
              filterWrapperEl.removeClass('filter-bar-in');
              hideKeyboard();
              scope.hideBackdrop();

              //Wait before cleaning up so element isn't removed before filter bar animates out
              $timeout(function () {
                scope.scrollItemsTop();
                scope.update(scope.items);

                scope.$destroy();
                element.remove();
                scope.cancelFilterBar.$scope = $scrollContainer = scrollView = filterWrapperEl = backdropEl = input = null;
                isShown = false;
                (done || angular.noop)();
              }, 350);
            });

            $timeout(function () {
              // wait to remove this due to a 300ms delay native
              // click which would trigging whatever was underneath this
              scope.container.removeClass('filter-bar-open');
            }, 400);

            scope.$deregisterBackButton();
            stateChangeListenDone();

            //unbind scroll event
            if ($scrollContainer) {
              $scrollContainer.off('scroll', handleScroll);
            }
          };

          // Appends the filterBar to the body.  Once the backdrop is hidden we can invoke done
          scope.showFilterBar = function(done) {
            if (scope.removed) return;

            scope.container.append(element).addClass('filter-bar-open');

            //scroll items to the top before starting the animation
            scope.scrollItemsTop();

            //start filterBar animation, show backrop and focus the input
            ionic.requestAnimationFrame(function () {
              if (scope.removed) return;

              $timeout(function () {
                filterWrapperEl.addClass('filter-bar-in');
                scope.focusInput();
                scope.showBackdrop();
                (done || angular.noop)();
              }, 20, false);
            });

            if ($scrollContainer) {
              $scrollContainer.on('scroll', handleScroll);
            }
          };

          // called when the user presses the backdrop, cancel/back button, changes state
          scope.cancelFilterBar = function() {
            // after the animation is out, call the cancel callback
            scope.removeFilterBar(scope.cancel);
          };

          scope.showFilterBar(scope.done);

          // Expose the scope on $ionFilterBar's return value for the sake of testing it.
          scope.cancelFilterBar.$scope = scope;

          return scope.cancelFilterBar;
        }

        return {
          show: filterBar
        };
      }]);


})(angular, ionic);

/* global angular,ionic */
(function (angular, ionic) {
  'use strict';

  angular.module('jett.ionic.scroll.sista', ['ionic'])
    .directive('scrollSista', ['$document', '$timeout', '$rootScope', '$ionicScrollDelegate', function($document, $timeout, $rootScope, $ionicScrollDelegate) {
      var TRANSITION_DELAY = 400;
      var defaultDelay = TRANSITION_DELAY * 2;
      var defaultDuration = TRANSITION_DELAY + 'ms';
      var scaleHeaderElements = ionic.Platform.isAndroid() ? false : true;

      function getParentWithAttr (e, attrName, attrValue, depth) {
        var attr;

        depth = depth || 10;
        while (e.parentNode && depth--) {
          attr = e.parentNode.getAttribute(attrName);
          if (attr && attr === attrValue) {
            return e.parentNode;
          }
          e = e.parentNode;
        }
        return null;
      }

      return {
        restrict: 'A',
        link: function($scope, $element, $attr) {
          var isNavBarTransitioning = true;
          var body = $document[0].body;
          var scrollDelegate = $attr.delegateHandle ? $ionicScrollDelegate.$getByHandle($attr.delegateHandle) : $ionicScrollDelegate;
          var scrollView = scrollDelegate.getScrollView();

          //coordinates
          var y, prevY, prevScrollTop;
          //headers
          var cachedHeader, activeHeader, headerHeight, contentTop;
          //subheader
          var subHeader, subHeaderHeight;
          //tabs
          var tabs, tabsHeight, hasTabsTop = false, hasTabsBottom = false;

          //y position that will indicate where specific elements should start and end their transition.
          var headerStart = 0;
          var tabsStart = 0;
          var subheaderStart = 0;
          var defaultEnd, headerEnd, tabsEnd, subheaderEnd;

          /**
           * translates an element along the y axis by the supplied value.  if duration is passed in,
           * a transition duration is set
           * @param element
           * @param y
           * @param duration
           */
          function translateY (element, y, duration) {
            if (duration && !element.style[ionic.CSS.TRANSITION_DURATION]) {
              element.style[ionic.CSS.TRANSITION_DURATION] = duration;
              $timeout(function () {
                element.style[ionic.CSS.TRANSITION_DURATION] = '';
              }, defaultDelay, false);
            }
            element.style[ionic.CSS.TRANSFORM] = 'translate3d(0, ' + (-y) + 'px, 0)';
          }

          /**
           * Initializes y and scroll variables
           */
          function initCoordinates () {
            y = 0;
            prevY = 0;
            prevScrollTop = 0;
          }

          /**
           * Initializes headers, tabs, and subheaders, and determines how they will transition on scroll
           */
          function init () {
            var activeView;

            cachedHeader = body.querySelector('[nav-bar="cached"] .bar-header');
            activeHeader = body.querySelector('[nav-bar="active"] .bar-header');

            if (!activeHeader) {
              return;
            }

            headerHeight = activeHeader.offsetHeight;
            contentTop = headerHeight;

            //since some people can have nested tabs, get the last tabs
            tabs = body.querySelectorAll('.tabs');
            tabs = tabs[tabs.length - 1];
            if (tabs) {
              tabsHeight = tabs.offsetHeight;
              if (tabs.parentNode.classList.contains('tabs-top')) {
                hasTabsTop = true;
                contentTop += tabsHeight;
              } else if (tabs.parentNode.classList.contains('tabs-bottom')) {
                hasTabsBottom = true;
              }
            }

            //subheader
            //since subheader is going to be nested in the active view, get the closest active view from $element and
            activeView = getParentWithAttr($element[0], 'nav-view', 'active');
            subHeader = activeView && activeView.querySelector('.bar-subheader');
            if (subHeader) {
              subHeaderHeight = subHeader.offsetHeight;
              contentTop += subHeaderHeight;
            }

            //set default end for header/tabs elements to scroll out of the scroll view and set elements end to default
            defaultEnd = contentTop * 2;
            headerEnd = tabsEnd = subheaderEnd = defaultEnd;

            //if tabs or subheader aren't available, set height to 0
            tabsHeight = tabsHeight || 0;
            subHeaderHeight = subHeaderHeight || 0;

            switch($attr.scrollSista) {
              case 'header':
                subheaderEnd =  headerHeight;
                tabsEnd = hasTabsTop ? headerHeight : 0;
                break;
              case 'header-tabs':
                headerStart = hasTabsTop ? tabsHeight : 0;
                subheaderEnd = hasTabsTop ? headerHeight + tabsHeight : headerHeight;
                break;
              case 'tabs-subheader':
                headerEnd = 0;
                headerStart = hasTabsTop ? contentTop - headerHeight : subHeaderHeight;
                tabsStart = hasTabsTop ? subHeaderHeight : 0;
                break;
              case 'tabs':
                headerEnd = 0;
                subheaderEnd =  hasTabsTop ? tabsHeight : 0;
                break;
              case 'subheader':
                headerEnd = 0;
                tabsEnd = 0;
                break;
              case 'header-subheader':
                tabsEnd = hasTabsTop ? headerHeight : 0;
                break;
              case 'subheader-header':
                headerStart = subHeaderHeight;
                tabsStart = hasTabsTop ? subHeaderHeight : 0;
                tabsEnd = hasTabsTop ? headerHeight : 0;
                break;
              //defaults to header-tabs-subheader
              default:
                headerStart = hasTabsTop ? contentTop - headerHeight : subHeaderHeight;
                tabsStart = hasTabsTop ? subHeaderHeight : 0;
            }
          }

          /**
           * Translates active and cached headers, and animates active children
           * @param y
           * @param duration
           */
          function translateHeaders (y, duration) {
            var fadeAmt = Math.max(0, 1 - (y / headerHeight));

            //translate active header
            if (activeHeader) {
              translateY(activeHeader, y, duration);
              angular.forEach(activeHeader.children, function (child) {
                child.style.opacity = fadeAmt;
                if (scaleHeaderElements) {
                  child.style[ionic.CSS.TRANSFORM] = 'scale(' + fadeAmt + ',' + fadeAmt + ')';
                }
              });
            }

            //translate cached header
            if (cachedHeader) {
              translateY(cachedHeader, y, duration);
            }
          }

          /**
           * Translates header, tabs, subheader elements and resets content top and/or bottom
           * When the active view leaves, we need sync functionality to reset headers and clear
           * @param y
           * @param duration
           */
          function translateElementsSync (y, duration) {
            var contentStyle = $element[0].style;
            var headerY = y > headerStart ? y - headerStart : 0;
            var tabsY, subheaderY;

            //subheader
            if (subHeader) {
              subheaderY =  y > subheaderStart ? y - subheaderStart : 0;
              translateY(subHeader, Math.min(subheaderEnd, subheaderY), duration);
            }

            //tabs
            if (tabs) {
              tabsY = Math.min(tabsEnd, y > tabsStart ? y - tabsStart : 0);

              if (hasTabsBottom) {
                tabsY = -tabsY;
                contentStyle.bottom = Math.max(0, tabsHeight - y) + 'px';
              }
              translateY(tabs, tabsY, duration);
            }

            //headers
            translateHeaders(Math.min(headerEnd, headerY), duration);

            //readjust top of ion-content
            contentStyle.top = Math.max(0, contentTop - y) + 'px';
          }

          /**
           * Translates header, tabs, subheader elements and resets content top and/or bottom
           * Wraps translate functionality in an animation frame request
           * @param y
           * @param duration
           */
          function translateElements (y, duration) {
            ionic.requestAnimationFrame(function() {
              translateElementsSync(y, duration);
            });
          }

          //Need to reinitialize the values on refreshComplete or things will get out of wack
          $scope.$on('scroll.refreshComplete', function () {
            initCoordinates();
          });

          /**
           * Before the active view leaves, reset elements, and reset the scroll container
           */
          $scope.$parent.$on('$ionicView.beforeLeave', function () {
            isNavBarTransitioning = true;
            translateElementsSync(0);
            activeHeader = null;
            cachedHeader = null;
          });

          /**
           * Scroll to the top when entering to reset then scrollView scrollTop. (prevents jumping)
           */
          $scope.$parent.$on('$ionicView.beforeEnter', function () {
            if (scrollView) {
              scrollView.scrollTo(0, 0);
            }
          });

          /**
           * Ionic sets the active/cached nav-bar AFTER the afterEnter event is called, so we need to set a small
           * timeout to let the nav-bar logic run.
           */
          $scope.$parent.$on('$ionicView.afterEnter', function () {
            initCoordinates();

            $timeout(function () {
              init();
              isNavBarTransitioning = false;
            }, 20, false);
          });

          /**
           * Called onScroll.  computes coordinates based on scroll position and translates accordingly
           */
          $element.bind('scroll', function (e) {
            if (isNavBarTransitioning) {
              return;
            }
            //support for jQuery event as well
            e = e.originalEvent || e;

            var duration = 0;
            var scrollTop = e.detail.scrollTop;

            y = scrollTop >= 0 ? Math.min(defaultEnd, Math.max(0, y + scrollTop - prevScrollTop)) : 0;

            //if we are at the bottom, animate the header/tabs back in
            if (scrollView.getScrollMax().top - scrollTop <= contentTop) {
              y = 0;
              duration = defaultDuration;
            }

            prevScrollTop = scrollTop;

            //if previous and current y are the same, no need to continue
            if (prevY === y) {
              return;
            }
            prevY = y;

            translateElements(y, duration);
          });

        }
      }
    }]);

})(angular, ionic);

/**
 * ==================  angular-ios9-uiwebview.patch.js v1.1.1 ==================
 *
 * This patch works around iOS9 UIWebView regression that causes infinite digest
 * errors in Angular.
 *
 * The patch can be applied to Angular 1.2.0 – 1.4.5. Newer versions of Angular
 * have the workaround baked in.
 *
 * To apply this patch load/bundle this file with your application and add a
 * dependency on the "ngIOS9UIWebViewPatch" module to your main app module.
 *
 * For example:
 *
 * ```
 * angular.module('myApp', ['ngRoute'])`
 * ```
 *
 * becomes
 *
 * ```
 * angular.module('myApp', ['ngRoute', 'ngIOS9UIWebViewPatch'])
 * ```
 *
 *
 * More info:
 * - https://openradar.appspot.com/22186109
 * - https://github.com/angular/angular.js/issues/12241
 * - https://github.com/driftyco/ionic/issues/4082
 *
 *
 * @license AngularJS
 * (c) 2010-2015 Google, Inc. http://angularjs.org
 * License: MIT
 */

angular.module('ngIOS9UIWebViewPatch', ['ng']).config(['$provide', function($provide) {
  'use strict';

  $provide.decorator('$browser', ['$delegate', '$window', function($delegate, $window) {

    if (isIOS9UIWebView($window.navigator.userAgent)) {
      return applyIOS9Shim($delegate);
    }

    return $delegate;

    function isIOS9UIWebView(userAgent) {
      return /(iPhone|iPad|iPod).* OS 9_\d/.test(userAgent) && !/Version\/9\./.test(userAgent);
    }

    function applyIOS9Shim(browser) {
      var pendingLocationUrl = null;
      var originalUrlFn= browser.url;

      browser.url = function() {
        if (arguments.length) {
          pendingLocationUrl = arguments[0];
          return originalUrlFn.apply(browser, arguments);
        }

        return pendingLocationUrl || originalUrlFn.apply(browser, arguments);
      };

      window.addEventListener('popstate', clearPendingLocationUrl, false);
      window.addEventListener('hashchange', clearPendingLocationUrl, false);

      function clearPendingLocationUrl() {
        pendingLocationUrl = null;
      }

      return browser;
    }
  }]);
}]);

/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    angular.module('App.pages', [
        'ui.router',
        'App.pages.class',
        'App.pages.member',
        'App.pages.dynamic'
    ])
})();

/**
 * 文字溢出，查看更多---插件
 */

(function() {
    'use strict';
    angular.module( 'ngTextTruncate', [] )
        .directive( "ngTextTruncate", [ "$compile", "ValidationServices", "CharBasedTruncation", "WordBasedTruncation",
            function( $compile, ValidationServices, CharBasedTruncation, WordBasedTruncation ) {
                return {
                    restrict: "A",
                    scope: {
                        text: "=ngTextTruncate",
                        charsThreshould: "@ngTtCharsThreshold",
                        wordsThreshould: "@ngTtWordsThreshold",
                        customMoreLabel: "@ngTtMoreLabel",
                        customLessLabel: "@ngTtLessLabel"
                    },
                    controller: ["$scope", "$element", "$attrs", function( $scope, $element, $attrs ) {
                        $scope.toggleShow = function() {
                            $scope.open = !$scope.open;
                        };

                        $scope.useToggling = $attrs.ngTtNoToggling === undefined;
                    }],
                    link: function( $scope, $element, $attrs ) {
                        $scope.open = false;

                        ValidationServices.failIfWrongThreshouldConfig( $scope.charsThreshould, $scope.wordsThreshould );

                        var CHARS_THRESHOLD = parseInt( $scope.charsThreshould );
                        var WORDS_THRESHOLD = parseInt( $scope.wordsThreshould );

                        $scope.$watch( "text", function() {
                            $element.empty();

                            if( CHARS_THRESHOLD ) {
                                if( $scope.text && CharBasedTruncation.truncationApplies( $scope, CHARS_THRESHOLD ) ) {
                                    CharBasedTruncation.applyTruncation( CHARS_THRESHOLD, $scope, $element );

                                } else {
                                    $element.append( $scope.text );
                                }

                            } else {

                                if( $scope.text && WordBasedTruncation.truncationApplies( $scope, WORDS_THRESHOLD ) ) {
                                    WordBasedTruncation.applyTruncation( WORDS_THRESHOLD, $scope, $element );

                                } else {
                                    $element.append( $scope.text );
                                }

                            }
                        } );
                    }
                };
            }] )



        .factory( "ValidationServices", function() {
            return {
                failIfWrongThreshouldConfig: function( firstThreshould, secondThreshould ) {
                    if( (! firstThreshould && ! secondThreshould) || (firstThreshould && secondThreshould) ) {
                        throw "You must specify one, and only one, type of threshould (chars or words)";
                    }
                }
            };
        })



        .factory( "CharBasedTruncation", [ "$compile", function( $compile ) {
            return {
                truncationApplies: function( $scope, threshould ) {
                    return $scope.text.length > threshould;
                },

                applyTruncation: function( threshould, $scope, $element ) {
                    if( $scope.useToggling ) {
                        var el = angular.element(    "<span>" +
                            $scope.text.substr( 0, threshould ) +
                            "<span ng-show='!open'>...</span>" +
                            "<span class='btn-link ngTruncateToggleText' " +
                            "ng-click='toggleShow()'" +
                            "ng-show='!open'>" +
                            " " + ($scope.customMoreLabel ? $scope.customMoreLabel : "More") +
                            "</span>" +
                            "<span ng-show='open'>" +
                            $scope.text.substring( threshould ) +
                            "<span class='btn-link ngTruncateToggleText'" +
                            "ng-click='toggleShow()'>" +
                            " " + ($scope.customLessLabel ? $scope.customLessLabel : "Less") +
                            "</span>" +
                            "</span>" +
                            "</span>" );
                        $compile( el )( $scope );
                        $element.append( el );

                    } else {
                        $element.append( $scope.text.substr( 0, threshould ) + "..." );

                    }
                }
            };
        }])



        .factory( "WordBasedTruncation", [ "$compile", function( $compile ) {
            return {
                truncationApplies: function( $scope, threshould ) {
                    return $scope.text.split( " " ).length > threshould;
                },

                applyTruncation: function( threshould, $scope, $element ) {
                    var splitText = $scope.text.split( " " );
                    if( $scope.useToggling ) {
                        var el = angular.element(    "<span>" +
                            splitText.slice( 0, threshould ).join( " " ) + " " +
                            "<span ng-show='!open'>...</span>" +
                            "<span class='btn-link ngTruncateToggleText' " +
                            "ng-click='toggleShow()'" +
                            "ng-show='!open'>" +
                            " " + ($scope.customMoreLabel ? $scope.customMoreLabel : "More") +
                            "</span>" +
                            "<span ng-show='open'>" +
                            splitText.slice( threshould, splitText.length ).join( " " ) +
                            "<span class='btn-link ngTruncateToggleText'" +
                            "ng-click='toggleShow()'>" +
                            " " + ($scope.customLessLabel ? $scope.customLessLabel : "Less") +
                            "</span>" +
                            "</span>" +
                            "</span>" );
                        $compile( el )( $scope );
                        $element.append( el );

                    } else {
                        $element.append( splitText.slice( 0, threshould ).join( " " ) + "..." );
                    }
                }
            };
        }]);

}());
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    angular.module('App.common')
        .directive('ngFileSelect', ngFileSelect);

    /**
     * input file 选择文件触发
     * @returns {{link: link}}
     */
    function ngFileSelect() {
        return {
            link: function($scope,el){
                el.bind("change", function(e){
                    $scope.file = (e.srcElement || e.target).files[0];
                    $scope.getFile();
                })
            }
        }
    }

})();
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    angular.module('App.common')
        .directive('photoPrevire', photoPrevire);

    /**
     * 精彩瞬间选择图片之后预览，
     * @returns {{restrict: string, link: link}}
     */
    function photoPrevire() {
        return {
            restrict:'E',
            replace :true,
            template:'<li><img class="full-image"></li>',
            link: function(scope, elem, attr) {
                scope.$watch('per',function(nowVal){
                    var img = nowVal;
                    var elem_child = elem[0].childNodes;
                    angular.forEach(elem_child,function(obj){
                        if(obj.nodeName == "IMG"){
                            obj.setAttribute('src',img.url);
                            obj.onclick=function(){
                                scope.previewImg(img.url,img.key);
                            }
                        }
                    })
                })

            }
        };
    }

})();
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    angular.module('App.common')
        .directive('textarea', textarea);


    /**
     * textarea 高度自适应
     * @returns {{restrict: string, link: link}}
     */
    function textarea() {
        return {
            restrict: 'E',
            link: function(scope, element, attr){
                var update = function(){
                    element.css("height", "auto");
                    var height = element[0].scrollHeight;
                    element.css("height", element[0].scrollHeight + "px");
                };
                scope.$watch(attr.ngModel, function(){
                    update();
                });
            }
        };
    }

})();
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    angular.module('App.common')
        .directive('wxImg', wxImg);


    /**
     * 微信选择图片之后预览，并绑定删除图片
     * @returns {{restrict: string, link: link}}
     */
    function wxImg() {
        return {
            restrict:'E',
            replace :true,
            template:'<li><img class="full-image"><i class="ion-close-circled removeImgBtn"></i></li>',
            link: function(scope, elem, attr) {
                scope.$watch('per',function(nowVal){
                    var img = nowVal;
                    var elem_child = elem[0].childNodes;
                    angular.forEach(elem_child,function(obj){
                        if(obj.nodeName == "IMG"){
                            obj.setAttribute('src',img.url);
                            obj.onclick=function(){
                                scope.previewImg(img.url);
                            }
                        }
                        if(obj.nodeName == "I"){
                            obj.onclick=function(){
                                scope.removePicture(img.url,img.imgIndex);
                            }
                        }

                    })
                })

            }
        };
    }

})();
/**
 * Created by hxpeng on 2017/3/24.
 */

/**
 * 全局异常处理
 */
(function () {
    'use strict';
    ApiCodeInterceptorConfiguration.$inject = ["$httpProvider"];
    angular.module('App.common')
        .config(ApiCodeInterceptorConfiguration);
    function ApiCodeInterceptorConfiguration($httpProvider) {

        ApiCodeInterceptor.$inject = ["$window", "$injector", "$q"];
        function ApiCodeInterceptor($window, $injector,$q) {
            return {
                request: function(config){
                    $injector.get('AppUtils').loading();
                    config.headers.auth_token = '1111';//设置请求头
                    return config;
                },
                requestError: function(err){
                    $injector.get('AppUtils').loadfinish();
                    return $q.reject(err);
                },
                response: function(res){
                    $injector.get('AppUtils').loadfinish();
                    return $q.resolve(res);
                },
                responseError: function(err){
                    $injector.get('AppUtils').loadfinish();
                    if(-1 === err.status) {
                        $injector.get('AppUtils').showAlert("远程服务器无响应!");
                    } else if(404 === err.status) {
                        console.log("找不到资源");
                    } else if(401 === err.status) {
                        console.log(err);
                        if(!$injector.get('AppUtils').isUndefinedOrNull(err.data)){
                            console.log("跳转页面到：" + err.data);
                            $window.location.href = err.data;
                            return false;
                            //event.preventDefault();
                            //console.log(1111111111111111);
                        }
                    } else if(400 === err.status) {
                        if(!$injector.get('AppUtils').isUndefinedOrNull(err.data)){
                            $injector.get('AppUtils').showAlert(err.data);
                        }else{
                            $injector.get('AppUtils').showAlert("缺失必要参数，请刷新页面重试！");
                        }
                    } else {
                        $injector.get('AppUtils').showAlert("发生错误,代码：" + err.status);
                    }
                    return $q.reject(err);
                }
            }
        }
        $httpProvider.interceptors.push(ApiCodeInterceptor)
    }
})();
/**
 * Created by hxpeng on 2017/3/25.
 */
(function () {
    'use strict';

    authRun.$inject = ["$rootScope", "$state", "Global", "store", "AppUtils", "$location"];
    angular.module('App')
        .run(authRun);

    //前端全局拦截登录
    function authRun($rootScope,$state,Global,store,AppUtils,$location) {

        $rootScope.$on('$locationChangeStart', function (event, next, current) {
            var url  = $location.path();
            var m = -1;
            var z;
            //路径?和#不能共存
            if(url.indexOf('?') != -1){
                m = url.indexOf('?');
            }
            if(url.indexOf('#') != -1){
                m = url.indexOf('#');
            }
            if(m != -1){
                z = url.substr(0, m);
            }else{
                z = url;
            }
            //console.log(z);
            if(z == "/member/bind" || z == "/member/bindInfomation" || z == "/member/init"){
                return true;
            }else{
                //store.set("gotoUrl",url);
                //var loginAccount = store.get('loginAccount');
                //if (AppUtils.isUndefinedOrNull(loginAccount)) {
                //    console.log("未找到会话中的用户,跳转至授权=========");
                //    $location.path('/member/bind');
                //}
            }
            //var restrictedPage = $.inArray($location.path(), ['/login', '/register']) === -1;
            //var loggedIn = $rootScope.globals.currentUser;
            //if (restrictedPage && !loggedIn) {
            //    $location.path('/login');
            //}
        });


        //监听路由变化之前
        $rootScope.$on('$stateChangeStart',function(event,toState,toParams,fromState,fromParams) {
        })

        //监听路由变化成功
        $rootScope.$on('$stateChangeSuccess',function(event,toState,toParams,fromState,fromParams){
        });

        //监听路由未找到
        $rootScope.$on('$stateNotFound',function(event,toState,toParams,fromState,fromParams){
        });
    }



})( );
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    AppUtils.$inject = ["$ionicPopup", "$ionicLoading", "$ionicScrollDelegate", "$window"];
    angular.module('App.common')
        .service('AppUtils', AppUtils);

    /**
     * 常用逻辑方法
     */
    function AppUtils($ionicPopup,$ionicLoading,$ionicScrollDelegate,$window) {

        return {
            isUndefinedOrNull: function isUndefinedOrNull(obj) {
                if(angular.isArray(obj)){
                    return obj==null||obj.length==0 ? true : false;
                }
                return !angular.isDefined(obj) || obj===null || obj=='';
            },
            showAlert: function showAlert(msg){
                $ionicPopup.alert({
                    title: '提示',
                    template: msg
                });
            },
            loading: function loading(){
                $ionicLoading.show({
                    content: 'Loading',
                    animation: 'fade-in',
                    showBackdrop: true,
                    maxWidth: 200,
                    showDelay: 0
                });
            },
            loadfinish: function loadfinish(){
                $ionicLoading.hide();
            },
            scrollTop: function scrollTop(){
                $ionicScrollDelegate.scrollTop();
            },
            goBack: function goBack(){
                $window.history.go(-1);
            }
        }
    }
})();
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    fileReader.$inject = ["$q"];
    angular.module('App.common')
        .service('fileReader', fileReader);

    /**
     * 文件read帮助
     */
    function fileReader($q){
        var onLoad = function(reader, deferred, scope) {
            return function () {
                scope.$apply(function () {
                    deferred.resolve(reader.result);
                });
            };
        };

        var onError = function (reader, deferred, scope) {
            return function () {
                scope.$apply(function () {
                    deferred.reject(reader.result);
                });
            };
        };

        var onProgress = function(reader, scope) {
            return function (event) {
                scope.$broadcast("fileProgress",
                    {
                        total: event.total,
                        loaded: event.loaded
                    });
            };
        };

        var getReader = function(deferred, scope) {
            var reader = new FileReader();
            reader.onload = onLoad(reader, deferred, scope);
            reader.onerror = onError(reader, deferred, scope);
            reader.onprogress = onProgress(reader, scope);
            return reader;
        };

        var readAsDataURL = function (file, scope) {
            var deferred = $q.defer();

            var reader = getReader(deferred, scope);
            reader.readAsDataURL(file);

            return deferred.promise;
        };

        return {
            readAsDataUrl: readAsDataURL
        };
    }
})();


/**
 * Created by hxpeng on 2017/3/24.
 */

(function () {
    'use strict';

    LocalStorageUtils.$inject = ["$window"];
    angular.module('App.common')
        .service("LocalStorageUtils",LocalStorageUtils)

    /**
     * 浏览器本地存储工具js
     * @param $window
     * @returns {{set: set, get: get, setObject: setObject, getObject: getObject}}
     * @constructor
     */
    function LocalStorageUtils($window) {
        return{
            //存储单个属性
            set :function(key,value){
                $window.localStorage[key]=value;
            },
            //读取单个属性
            get:function(key){
                return  $window.localStorage[key];
            },
            //存储对象，以JSON格式存储
            setObject:function(key,value){
                $window.localStorage[key]=JSON.stringify(value);
            },
            //读取对象
            getObject: function (key) {
                return JSON.parse($window.localStorage[key] || '{}');
            }
        }
    }
})();




/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    routeConfig.$inject = ["$stateProvider"];
    angular.module('App.pages.class', [])
        .config(routeConfig);

    function routeConfig($stateProvider) {

        $stateProvider.state('classMenu', {
            url: "/class",
            abstract: true,
            templateUrl: 'source/pages/page-tab.html',
        }).state('classMenu.index', {
            url: "/index",
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/class/index/index.html',
                    controller:'ClassCtrl as vm'
                }
            }
        }).state('classMenu.classInfo', {
            url: "/classInfo",
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/class/info/index.html',
                    controller:'ClassInfoCtrl as vm'
                }
            }
        }).state('classMenu.classNotice',{
            url: "/classNotice",
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/class/notice/list.html',
                    controller:'ClassNoticeCtrl as vm'
                }
            }
        }).state('classMenu.noticeInfo',{
            url: "/noticeInfo/{noticeId:string}",
            params: {
                noticeId: null
            },
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/class/notice/index.html',
                    controller: 'ClassNoticeInfoCtrl as vm',
                    resolve: {
                        noticeId: ["$stateParams", function($stateParams){
                            return $stateParams.noticeId;
                        }],
                    }
                }
            }
        }).state('classMenu.classActivity',{
            url: "/classActivity",
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/class/activity/list.html',
                    controller: 'ClassActivityCtrl as vm'
                }
            }
        }).state('classMenu.activityInfo',{
            url: "/activityInfo/{activityId:string}",
            params: {
                activityId: null
            },
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/class/activity/index.html',
                    controller: 'ClassActivityInfoCtrl as vm',
                    resolve: {
                        activityId: ["$stateParams", function($stateParams){
                            return $stateParams.activityId;
                        }],
                    }
                }
            }
        });
    }

})();
/**
 * Created by hxpeng on 2017/3/24.
 */

(function () {
    'use strict';

    ClassModel.$inject = ["API", "$resource"];
    angular.module('App.pages.class')
        .service('ClassModel', ClassModel);

    function ClassModel(API,$resource) {

        this.actions = {}
        this.actions.search = {
            method: 'POST',
            url: API + '/console/2.0/user/list'
        }
        return $resource.call(this, this.actions)
    }

})();
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    routeConfig.$inject = ["$stateProvider", "$urlRouterProvider"];
    angular.module('App.pages.dynamic', [])
        .config(routeConfig);

    function routeConfig($stateProvider,$urlRouterProvider) {
        $stateProvider.state('dynamic', {
            url: "/dynamic",
            abstract: true,
            templateUrl: 'source/pages/page-tab.html',
        }).state('dynamic.index', {
            url: "/index",
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/dynamic/index.html',
                    controller:'DynamicCtrl as vm'
                }
            }
        }).state('dynamic.create', {
            url: "/create",
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/dynamic/create.html',
                    controller:'DynamicCreateCtrl as vm'
                }
            }
        });
    }
})();
/**
 * Created by hxpeng on 2017/4/18.
 */
(function () {
    'use strict';

    DynamicCreateCtrl.$inject = ["$rootScope", "store", "$scope", "$state", "AppUtils", "MemberModel", "$location", "$http", "Global"];
    angular.module('App.pages.dynamic')
        .controller('DynamicCreateCtrl', DynamicCreateCtrl);

    function DynamicCreateCtrl($rootScope,store,$scope,$state,AppUtils,MemberModel,$location,$http,Global) {
        //$scope.test= true;
        $scope.buttons = [{
            label: 'a link text',
            icon: 'ion-paper-airplane'
        },{
            label: 'another link',
            icon: 'ion-plus'
        },{
            label: 'a third link',
            icon: 'ion-paperclip'
        }];


        $('a.target-burger').click(function(e){
            $(' nav.main-nav, a.target-burger').toggleClass('toggled');
            $('div.screen').toggleClass("screen-fixed");
            e.preventDefault();
        });

    }

})();

/**
 * Created by hxpeng on 2017/4/18.
 */
(function () {
    'use strict';

    DynamicCtrl.$inject = ["$rootScope", "store", "$scope", "$state", "AppUtils", "MemberModel", "$location", "$http", "Global"];
    angular.module('App.pages.dynamic')
        .controller('DynamicCtrl', DynamicCtrl);

    function DynamicCtrl($rootScope,store,$scope,$state,AppUtils,MemberModel,$location,$http,Global) {
        //$scope.test= true;
        $scope.buttons = [{
            label: 'a link text',
            icon: 'ion-paper-airplane'
        },{
            label: 'another link',
            icon: 'ion-plus'
        },{
            label: 'a third link',
            icon: 'ion-paperclip'
        }];

        //页面进入先绑定事件，（即使是缓存页面也会执行）
        $scope.$on('$ionicView.enter', function(){
            $element.prop("onclick", null);
            $('a.target-burger').click(function(e){
                console.log(1111);
                $('nav.main-nav, a.target-burger').toggleClass('toggled');
                $('div.screen').toggleClass("screen-fixed");
                e.preventDefault();
            });
        });

        $scope.$on('$ionicView.beforeLeave', function(){
            $('nav.main-nav, a.target-burger').toggleClass('toggled');
            $('div.screen').toggleClass("screen-fixed");
        });

        $scope.createNewDynamic = function(){
            $location.path('/dynamic/create');
        }





    }

})();

/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    routeConfig.$inject = ["$stateProvider", "$urlRouterProvider"];
    angular.module('App.pages.member', [])
        .config(routeConfig);

    function routeConfig($stateProvider,$urlRouterProvider) {
        $stateProvider.state('memberMenu', {
            url: "/member",
            abstract: true,
            templateUrl: 'source/pages/page-tab.html',
        }).state('memberMenu.bind', {
            url: "/bind",
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/member/bind/auth.html',
                    controller:'AuthCtrl as vm'
                }
            }
        }).state('memberMenu.bindInfomation', {
            url: "/bindInfomation?{authId:string}",
            params: {
                authId: null
            },
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/member/bind/bind-wechat.html',
                    controller:'BindCtrl as vm',
                    resolve: {
                        authId: ["$stateParams", function($stateParams){
                            return $stateParams.authId;
                        }]
                    }
                }
            }
        }).state('memberMenu.bindResult', {
            url: "/bindResult",
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/member/bind/bind-result.html',
                    controller:'BindCtrl as vm'
                }
            }
        }).state('memberMenu.teacherIndex', {
            url: "/teacherIndex",
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/member/teacher/index.html',
                    controller:'TeacherCtrl as vm'
                }
            }
        }).state('memberMenu.parentIndex', {
            url: "/parentIndex",
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/member/parent/index.html',
                    controller:'ParentCtrl as vm'
                }
            }
        }).state('memberMenu.studentIndex', {
            url: "/studentIndex/{studentId:string}",
            params: {
                studentId: null
            },
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/member/student/index.html',
                    controller:'StudentCtrl as vm',
                    resolve: {
                        studentId: ["$stateParams", function($stateParams){
                            return $stateParams.studentId;
                        }]
                    }
                }
            }
        }).state('memberMenu.parentInfo', {
            url: "/parentInfo/{studentId:string}",
            params: {
                studentId: null
            },
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/member/parent/parent-info.html',
                    controller:'ParentInfoCtrl as vm',
                    resolve: {
                        studentId: ["$stateParams", function($stateParams){
                            return $stateParams.studentId;
                        }]
                    }
                }
            }
        }).state('memberMenu.parentEntrustList', {
            url: "/parentEntrustList",
            cache: true,
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/member/entrust/parent-entrust-list.html',
                    controller:'ParentEntrustCtrl as vm'
                }
            }
        }).state('memberMenu.newEntrust', {
            url: "/newEntrust/",
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/member/entrust/parent-new-entrust.html',
                    controller:'ParentNewEntrustCtrl as vm'
                }
            }
        }).state('memberMenu.parentEntrustInfo', {
            url: "/parentEntrustInfo/{entrustId:string}",
            cache: false,
            params: {
                entrustId: null
            },
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/member/entrust/parent-entrust-info.html',
                    controller:'ParentEntrustInfoCtrl as vm',
                    resolve: {
                        entrustId: ["$stateParams", function($stateParams){
                            return $stateParams.entrustId;
                        }]
                    }
                }
            }
        }).state('memberMenu.teacherEntrustList', {
            url: "/teacherEntrustList",
            cache: true,
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/member/entrust/teacher-entrust-list.html',
                    controller:'TeacherEntrustCtrl as vm'
                }
            }
        }).state('memberMenu.teacherEntrustInfo', {
            url: "/teacherEntrustInfo/{entrustId:string}",
            cache: false,
            params: {
                entrustId: null
            },
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/member/entrust/teacher-entrust-info.html',
                    controller:'TeacherEntrustInfoCtrl as vm',
                    resolve: {
                        entrustId: ["$stateParams", function($stateParams){
                            return $stateParams.entrustId;
                        }]
                    }
                }
            }
        }).state('memberMenu.leaveMsg', {
            url: "/leaveMsg/{toMemberId:string}",
            params:{
                toMemberId:null
            },
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/member/msg/index.html',
                    controller:'MsgCtrl as vm'
                }
            }
        }).state('memberMenu.display', {
            url: "/display",
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/member/upload/display.html',
                    controller:'DisplayCtrl as vm'
                }
            }
        }).state('memberMenu.upload', {
            url: "/upload",
            views: {
                'kinder-view': {
                    templateUrl: 'source/pages/member/upload/upload.html',
                    controller:'UploadCtrl as vm'
                }
            }
        });
    }
})();
/**
 * Created by hxpeng on 2017/3/24.
 */

(function () {
    'use strict';

    MemberModel.$inject = ["API", "$resource"];
    angular.module('App.pages.member')
        .service('MemberModel', MemberModel);

    function MemberModel(API,$resource) {
        this.actions = {}

        /**
         * 根据父母成员找到学生成员
         * @type {{method: string, url: string}}
         */
        this.actions.findStudentByParentId = {
            method: 'POST',
            url: API + '/member/findStudentByParentId'
        }
        /**
         * 获取成员信息（id）
         * @type {{method: string, url: string}}
         */
        this.actions.findLoginAccountById = {
            method: 'POST',
            url: API + '/member/findLoginAccountById'
        }
        /**
         * 获取成员信息（id,类别）
         * @type {{method: string, url: string}}
         */
        this.actions.getMemberInfo = {
            method: 'POST',
            url: API + '/member/getMemberInfo'
        }
        /**
         * 和微信号绑定
         * @type {{method: string, url: string}}
         */
        this.actions.bindWeChatInfo = {
            method: 'POST',
            url: API + '/member/bindWeChatInfo'
        }
        /**
         * 获取父母成员信息
         * @type {{method: string, url: string}}
         */
        this.actions.getParentInfo = {
            method: 'POST',
            url: API + '/member/getParentInfo'
        }
        /**
         * 保存成员信息
         * @type {{method: string, url: string}}
         */
        this.actions.saveParentMemberInfo = {
            method: 'POST',
            url: API + '/member/saveParentMemberInfo'
        }

        /**
         *提交微信返回上传图片的serverId数组
         * @type {{method: string, url: string}}
         */
        this.actions.submitUploadImg = {
            method: 'POST',
            url: API + '/member/submitUploadImg'
        }

        /**
         * 精彩瞬间
         * @type {{method: string, url: string}}
         */
        this.actions.queryClassPhoto = {
            method: 'POST',
            url: API + '/member/queryClassPhoto'
        }

        /**
         * 查找学生列表
         * @type {{method: string, url: string}}
         */
        this.actions.getStudentList = {
            method: 'POST',
            url: API + '/class/getStudentList'
        }

        /**
         * 返回父母成员ID
         * @type {{method: string, url: string}}
         */
        this.actions.getParentId = {
            method: 'POST',
            url: API + '/member/getParentId'
        }



        return $resource.call(this, this.url, this.params, this.actions)
    }

})();
/**
 * Created by dzd on 2017/3/24.
 */
(function () {
    'use strict';

    ClassActivityCtrl.$inject = ["$scope", "$state", "ClassActivityModel", "AppUtils"];
    angular.module('App.pages.class')
        .controller('ClassActivityCtrl', ClassActivityCtrl);

    function ClassActivityCtrl($scope,$state,ClassActivityModel,AppUtils) {

        $scope.$on('$ionicView.beforeEnter', function (event, viewData) {
            viewData.enableBack = true;
        });
        $scope.gotoDetail = function(activityId){
            if(!AppUtils.isUndefinedOrNull(activityId)){
                $state.go("classMenu.activityInfo",{activityId:activityId});
            }else{
                AppUtils.showAlert("请选择要查看的活动！");
            }
        }

        var vm = this;
        vm.exhortaions = [];
        vm.loadMoreBtnStatus = true;
        vm.loadMoreBtnStr = "加载更多";
        vm.pageIndex = 1;//第一页

        $scope.loadMoreActivity = function(){
            if(vm.loadMoreBtnStatus){
                vm.pageIndex = vm.pageIndex + 1;
                vm.getActivityPage();
            }
        }

        vm.getActivityPage = function(){
            ClassActivityModel.getActivityPage({
                classId : 88,
                pageInfo: {
                    pageSize: 5,
                    pageNumber: vm.pageIndex
                }
            }).$promise.then(function(response){
                if(response.stat == 'err'){
                    AppUtils.showAlert(response.msg);
                }else{
                    var reponseDate = response.pageResult;
                    var items = reponseDate.pageResult;
                    var pageIndex = reponseDate.pageIndex;
                    var pageTotalPageSize = reponseDate.pageTotalPageSize;
                    if(pageIndex == pageTotalPageSize || items.length == 0){
                        vm.loadMoreBtnStatus = false;
                        vm.loadMoreBtnStr = "没有更多数据了";
                    }
                    angular.forEach(items,function(data){
                        vm.exhortaions.push(data);
                    })
                }
            })
        }
        vm.getActivityPage();
    }
})();
/**
 * Created by dzd on 2017/3/24.
 */
(function () {
    'use strict';

    ClassActivityInfoCtrl.$inject = ["activityId", "$scope", "$state", "AppUtils", "ClassActivityModel"];
    angular.module('App.pages.class')
        .controller('ClassActivityInfoCtrl', ClassActivityInfoCtrl);

    function ClassActivityInfoCtrl(activityId,$scope,$state,AppUtils,ClassActivityModel) {

        $scope.$on('$ionicView.beforeEnter', function (event, viewData) {
            viewData.enableBack = true;
        });

        var vm = this;
        vm.classActivity = {};
        vm.init = function(){
            if(!AppUtils.isUndefinedOrNull(activityId)){
                ClassActivityModel.findClassActivity({id: activityId}).$promise.then(function(response){
                    if(response.stat == 'err'){
                        AppUtils.showAlert(response.msg);
                    }else{
                        vm.classActivity = response.classActivity;
                    }
                })
            }else{
                AppUtils.showAlert("未找到该活动！");
                $state.go("classMenu.classActivity",activityId);
            }
        }
        vm.init();
    }
})();


/**
 * Created by dzd on 2017/3/24.
 */

(function () {
    'use strict';

    ClassActivityModel.$inject = ["API", "$resource"];
    angular.module('App.pages.class')
        .service('ClassActivityModel', ClassActivityModel);

    function ClassActivityModel(API,$resource) {
        this.actions = {}

        this.actions.findClassActivity = {
            method: 'GET',
            url: API + '/activity/wechat/findClassActivity'
        }

        this.actions.getActivityPage = {
            method: 'POST',
            url: API + '/activity/wechat/getActivityPage'
        }
        return $resource.call(this, this.url, this.params, this.actions)
    }

})();
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    ClassCtrl.$inject = ["$scope", "$ionicSlideBoxDelegate"];
    angular.module('App.pages.class')
        .controller('ClassCtrl', ClassCtrl);

    function ClassCtrl($scope,$ionicSlideBoxDelegate) {

        var vm = this;
        $scope.next = function() {
            $ionicSlideBoxDelegate.next();
        };
        $scope.previous = function() {
            $ionicSlideBoxDelegate.previous();
        };
        $scope.slideChanged = function(index) {
            $scope.slideIndex = index;
        };
        $ionicSlideBoxDelegate.loop(true); //解决轮播至最后一个不轮播的问题

    }

})();
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    ClassInfoCtrl.$inject = ["$scope", "ClassInfoModel", "AppUtils", "store", "MemberModel"];
    angular.module('App.pages.class')
        .controller('ClassInfoCtrl', ClassInfoCtrl);

    function ClassInfoCtrl($scope,ClassInfoModel,AppUtils,store,MemberModel) {

        $scope.$on('$ionicView.beforeEnter', function (event, viewData) {
            viewData.enableBack = true;
        });

        var vm = this;
        vm.classInfo = {};
        var loginAccount = store.get("loginAccount");
        var memberId = "";
        if(loginAccount.memberType == 2){
            memberId = loginAccount.studentId;
        }else{
            memberId = loginAccount.memberId;
        }

        ClassInfoModel.classInfo({memberId: memberId}).$promise.then(function(response){
            if(response.stat == 'err'){
                AppUtils.showAlert(response.msg);
            }else{
                vm.classInfo = response.schoolClass;
            }
        })

    }

})();

/**
 * Created by hxpeng on 2017/3/24.
 */

(function () {
    'use strict';

    ClassInfoModel.$inject = ["API", "$resource"];
    angular.module('App.pages.class')
        .service('ClassInfoModel', ClassInfoModel);

    function ClassInfoModel(API,$resource) {
        this.actions = {}
        this.actions.classInfo = {
            method: 'GET',
            url: API + '/class/findClassByMemberId'
        }
        return $resource.call(this, this.url, this.params, this.actions)
    }

})();
/**
 * Created by dzd on 2017/3/24.
 */
(function () {
    'use strict';

    ClassNoticeCtrl.$inject = ["$state", "$scope", "ClassNoticeModel", "AppUtils"];
    angular.module('App.pages.class')
        .controller('ClassNoticeCtrl', ClassNoticeCtrl);

    function ClassNoticeCtrl($state,$scope,ClassNoticeModel,AppUtils) {

        $scope.$on('$ionicView.beforeEnter', function (event, viewData) {
            viewData.enableBack = true;
        });

        $scope.gotoDetail = function(noticeId){
            if(!AppUtils.isUndefinedOrNull(noticeId)){
                $state.go("classMenu.noticeInfo",{noticeId:noticeId});
            }else{
                AppUtils.showAlert("请选择要查看的活动！");
            }
        }

        var vm = this;
        vm.exhortaions = [];
        vm.loadMoreBtnStatus = true;
        vm.loadMoreBtnStr = "加载更多";
        vm.pageIndex = 1;//第一页

        $scope.loadMoreNotice = function(){
            if(vm.loadMoreBtnStatus){
                vm.pageIndex = vm.pageIndex + 1;
                vm.getNoticePage();
            }
        }
        vm.getNoticePage = function(){
            ClassNoticeModel.getNoticePage({
                classId : 18,
                pageInfo: {
                    pageSize: 5,
                    pageNumber: vm.pageIndex
                }
            }).$promise.then(function(response){
                if(response.stat == 'err'){
                    AppUtils.showAlert(response.msg);
                }else{
                    var reponseDate = response.pageResult;
                    var items = reponseDate.pageResult;
                    var pageIndex = reponseDate.pageIndex;
                    var pageTotalPageSize = reponseDate.pageTotalPageSize;
                    if(pageIndex == pageTotalPageSize || items.length == 0){
                        vm.loadMoreBtnStatus = false;
                        vm.loadMoreBtnStr = "没有更多数据了";
                    }
                    angular.forEach(items,function(data){
                        vm.exhortaions.push(data);
                    })
                }
            })
        }
        vm.getNoticePage();
    }

})();

/**
 * Created by dzd on 2017/3/24.
 */
(function () {
    'use strict';

    ClassNoticeInfoCtrl.$inject = ["noticeId", "$state", "$scope", "ClassNoticeModel", "AppUtils"];
    angular.module('App.pages.class')
        .controller('ClassNoticeInfoCtrl', ClassNoticeInfoCtrl);

    function ClassNoticeInfoCtrl(noticeId,$state,$scope,ClassNoticeModel,AppUtils) {

        $scope.$on('$ionicView.beforeEnter', function (event, viewData) {
            viewData.enableBack = true;
        });

        var vm = this;
        vm.classNotice = {};
        vm.init = function(){
            if(!AppUtils.isUndefinedOrNull(noticeId)){
                ClassNoticeModel.findClassNotice({id: noticeId}).$promise.then(function(response){
                    if(response.stat == 'err'){
                        AppUtils.showAlert(response.msg);
                    }else{
                        vm.classNotice = response.classNotice;
                    }
                })
            }else{
                AppUtils.showAlert("未找到该活动！");
                $state.go("classMenu.classNotice",noticeId);
            }
        }
        vm.init();
    }

})();
/**
 * Created by hxpeng on 2017/3/24.
 */

(function () {
    'use strict';

    ClassNoticeModel.$inject = ["API", "$resource"];
    angular.module('App.pages.class')
        .service('ClassNoticeModel', ClassNoticeModel);

    function ClassNoticeModel(API,$resource) {
        this.actions = {}
        this.actions.findClassNotice = {
            method: 'GET',
            url: API + '/notice/wechat/findClassNotice'
        }
        this.actions.getNoticePage = {
            method: 'POST',
            url: API + '/notice/wechat/getNoticePage'
        }
        return $resource.call(this, this.url, this.params, this.actions)
    }

})();

/**
 * Created by hxpeng on 2017/3/27.
 */

(function () {
    'use strict';

    AuthCtrl.$inject = ["$http", "Global", "AppUtils", "store", "$location"];
    angular.module('App.pages.member')
        .controller('AuthCtrl', AuthCtrl);

    function AuthCtrl($http,Global,AppUtils,store,$location) {
        var loginAccount = store.get("loginAccount");
        if(AppUtils.isUndefinedOrNull(loginAccount)){
            $http.post(Global.path.server_wechat_test_path, {})
                .success(function (response) {
                    loginAccount = response.loginAccountVo;
                    if(AppUtils.isUndefinedOrNull(loginAccount.memberId)){
                        $location.path("/member/bindInfomation?authId=" + loginAccount.openId);
                    }
                    store.set('loginAccount', loginAccount);
                    var gotoUrl = store.get("gotoUrl");
                    if(!AppUtils.isUndefinedOrNull(gotoUrl) && gotoUrl != '/'){
                        $location.path(gotoUrl);
                    }else{
                        if(loginAccount.memberType == 2){
                            $location.path("/member/parentIndex");
                        }else if(loginAccount.memberType == 1){
                            $location.path("/member/teacherIndex");
                        }
                    }
                })
                .error(function () {
                    console.log("err.....");
                })
        }else{
            if(loginAccount.memberType == 2){
                $location.path("/member/parentIndex");
            }else if(loginAccount.memberType == 1){
                $location.path("/member/teacherIndex");
            }
        }

    }

})();

/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    BindCtrl.$inject = ["$rootScope", "authId", "store", "$scope", "$state", "AppUtils", "MemberModel", "$location", "$http", "Global"];
    angular.module('App.pages.member')
        .controller('BindCtrl', BindCtrl);

    function BindCtrl($rootScope,authId,store,$scope,$state,AppUtils,MemberModel,$location,$http,Global) {


        //暂搁置扫码绑定成员
        //var currentPath = $location.url();
        //if(currentPath.indexOf("#") != -1){
        //    currentPath = currentPath.split('#')[0];
        //}
        //currentPath = Global.path.wechat_path + currentPath;
        //console.log(currentPath);
        //$http.post(Global.path.server_sdk_auth_path,{"url":currentPath})
        //    .success(function(data){
        //        wx.config({
        //            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        //            appId: data.appId, // 必填，公众号的唯一标识
        //            timestamp: data.timestamp, // 必填，生成签名的时间戳
        //            nonceStr: data.noncestr, // 必填，生成签名的随机串
        //            signature: data.signature,// 必填，签名，见附录1
        //            jsApiList: ['scanQRCode'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        //        });
        //        /**
        //         * 如果需要页面加载就执行微信sdk接口，把接口放入wx.read即可
        //         */
        //        //wx.ready(function () {
        //        //});
        //        wx.error(function(res){
        //            console.log(res);
        //            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，
        //            // 也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        //
        //        });
        //    })
        //    .error(function(data,header,config,status){
        //        console.log("请求微信sdk校验异常");
        //    });
        //$scope.scanQode = function(){
        //    wx.scanQRCode({
        //        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        //        scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
        //        success: function (res) {
        //            var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
        //            alert(result);
        //            //$("input[name='jsonParams']").val(result);
        //            //$("form").submit();
        //        }
        //    });
        //}


        var vm = this;
        vm.authId = authId;
        vm.bindResult = false;
        vm.memberVo = {};
        vm.mustBindStat = false;

        vm.init = function(){
            MemberModel.findLoginAccountById({id:authId}).$promise.then(function(response){
                var loginAccountVo = response.loginAccountVo;
                if(AppUtils.isUndefinedOrNull(loginAccountVo)){
                    vm.mustBindStat = true;
                }else{
                    store.set('loginAccount', loginAccountVo);
                    var gotoUrl = store.get("gotoUrl");
                    if(!AppUtils.isUndefinedOrNull(gotoUrl) && gotoUrl != '/'){
                        $location.path(gotoUrl);
                    }else{
                        if(loginAccountVo.memberType == 2){
                            $location.path("/member/parentIndex");
                        }else if(loginAccountVo.memberType == 1){
                            $location.path("/member/teacherIndex");
                        }
                    }
                }

            })
        }
        vm.init();

        $scope.showTypeChooseBtn = true;
        $scope.bindParentStatus = false;
        $scope.bindTeacherStatus = false;


        $scope.bindInfo = function(type){
            $scope.showTypeChooseBtn = false;
            vm.memberVo = {};
            if(type == "parent"){
                $scope.bindParentStatus = true;
            }else if(type == "teacher"){
                $scope.bindTeacherStatus = true;
            }else{
                $scope.showTypeChooseBtn = true;
                $scope.bindParentStatus = false;
                $scope.bindTeacherStatus = false;
            }
        }


        $scope.submitParentInfo = function(){
            vm.memberVo.memberType = "2";
            if(AppUtils.isUndefinedOrNull(vm.memberVo.studentNumber)){
                AppUtils.showAlert("请输入学生学号！");
                return false;
            }
            if(AppUtils.isUndefinedOrNull(vm.memberVo.studentName)){
                AppUtils.showAlert("请输入学生姓名！");
                return false;
            }
            if(AppUtils.isUndefinedOrNull(vm.memberVo.memberName)){
                AppUtils.showAlert("请输入家长姓名！");
                return false;
            }
            if(AppUtils.isUndefinedOrNull(vm.memberVo.memberPhone)){
                AppUtils.showAlert("请输入家长的手机号码！");
                return false;
            }
            $scope.postMemberInfo();
        }
        $scope.submitTeacherInfo = function(){
            vm.memberVo.memberType = "1";
            if(AppUtils.isUndefinedOrNull(vm.memberVo.className)){
                AppUtils.showAlert("请输入学生学号！");
                return false;
            }
            if(AppUtils.isUndefinedOrNull(vm.memberVo.memberName)){
                AppUtils.showAlert("请输入教师姓名！");
                return false;
            }
            if(AppUtils.isUndefinedOrNull(vm.memberVo.memberPhone)){
                AppUtils.showAlert("请输入教师的手机号码！");
                return false;
            }
            $scope.postMemberInfo();
        }
        $scope.postMemberInfo = function(){
            vm.memberVo.openId = authId;
            MemberModel.bindWeChatInfo(vm.memberVo).$promise.then(function(response){
                if(response.stat == 'err'){
                    AppUtils.showAlert(response.msg);
                }else{
                    var loginAccountVo = response.loginAccountVo;
                    store.set('loginAccount', loginAccountVo);

                    AppUtils.showAlert("绑定成功！");
                    var gotoUrl = store.get("gotoUrl");
                    if(!AppUtils.isUndefinedOrNull(gotoUrl)){
                        $location.path(gotoUrl);
                    }else{
                        if(loginAccountVo.memberType == 2){
                            $location.path("/member/parentIndex");
                        }else if(loginAccountVo.memberType == 1){
                            $location.path("/member/teacherIndex");
                        }
                    }

                }
            })
        }



    }

})();

/**
 * Created by hxpeng on 2017/3/24.
 */

(function () {
    'use strict';
    EntrustModel.$inject = ["API", "$resource"];
    angular.module('App.pages.member')
        .service('EntrustModel', EntrustModel);

    function EntrustModel(API,$resource) {
        this.actions = {}
        this.actions.getEntrustPage = {
            method: 'POST',
            url: API + '/entrust/getEntrustPage'
        }
        this.actions.getEntrustInfo = {
            method: 'GET',
            url: API + '/entrust/getEntrustInfo'
        }
        this.actions.saveEntrust = {
            method: 'POST',
            url: API + '/entrust/saveEntrust'
        }
        this.actions.executedEntrust = {
            method: 'GET',
            url: API + '/entrust/executedEntrust'
        }
        return $resource.call(this, this.url, this.params, this.actions)
    }
})();
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    ParentEntrustCtrl.$inject = ["$scope", "$state", "EntrustModel", "AppUtils", "store"];
    angular.module('App.pages.member')
        .controller('ParentEntrustCtrl', ParentEntrustCtrl);

    function ParentEntrustCtrl($scope,$state,EntrustModel,AppUtils,store) {

        $scope.$on('$ionicView.beforeEnter', function (event, viewData) {
            viewData.enableBack = true;
        });

        $scope.gotoDetail = function(entrustId){
            if(!AppUtils.isUndefinedOrNull(entrustId)){
                $state.go("memberMenu.teacherEntrustInfo",{entrustId:entrustId});
            }else{
                AppUtils.showAlert("请选择要查看的嘱托！");
            }
        }


        var vm = this;
        vm.exhortaions = [];
        vm.loadMoreBtnStatus = true;
        vm.loadMoreBtnStr = "加载更多";
        vm.pageIndex = 1;//第一页

        $scope.loadMoreEntrust = function(){
            if(vm.loadMoreBtnStatus){
                vm.pageIndex = vm.pageIndex + 1;
                vm.getEntrustPage();
            }
        }

        var loginAccount = store.get("loginAccount");
        vm.getEntrustPage = function(){
            EntrustModel.getEntrustPage({
                entrustState: vm.entrustStatusParams,
                //entrustId: loginAccount.memberId,
                entrustId: 'A83FA905F6044E9CA30C52FDCD351794',
                pageInfo: {
                    pageSize: 5,
                    pageNumber: vm.pageIndex
                }
            }).$promise.then(function(response){
                if(response.stat == 'err'){
                    AppUtils.showAlert(response.msg);
                }else{
                    var reponseDate = response.pageResult;
                    var items = reponseDate.pageResult;
                    var pageIndex = reponseDate.pageIndex;
                    var pageTotalPageSize = reponseDate.pageTotalPageSize;
                    if(pageIndex == pageTotalPageSize || items.length == 0){
                        vm.loadMoreBtnStatus = false;
                        vm.loadMoreBtnStr = "没有更多数据了";
                    }
                    angular.forEach(items,function(data){
                        vm.exhortaions.push(data);
                    })
                }
            })
        }

        vm.entrustTitle = "嘱托列表";
        vm.isUnsolved = true;
        vm.getEntrustPage();
    }

})();
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    ParentEntrustInfoCtrl.$inject = ["entrustId", "$scope", "$state", "EntrustModel", "AppUtils"];
    angular.module('App.pages.member')
        .controller('ParentEntrustInfoCtrl', ParentEntrustInfoCtrl);

    function ParentEntrustInfoCtrl(entrustId,$scope,$state,EntrustModel,AppUtils) {
        $scope.$on('$ionicView.beforeEnter', function (event, viewData) {
            viewData.enableBack = true;
        });

        var vm = this;
        vm.init = function(){
            if(!AppUtils.isUndefinedOrNull(entrustId)){
                EntrustModel.getEntrustInfo({entrustId: entrustId}).$promise.then(function(response){
                    if(response.stat == 'err'){
                        AppUtils.showAlert(response.msg);
                    }else{
                        vm.entrust = response.entrust;
                    }
                })
            }else{
                AppUtils.showAlert("未找到该嘱托！");
                $state.go("memberMenu.entrust",entrustId);
            }
        }
        vm.init();
    }

})();
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    ParentNewEntrustCtrl.$inject = ["$scope", "$state", "EntrustModel", "AppUtils", "store", "$stateParams"];
    angular.module('App.pages.member')
        .controller('ParentNewEntrustCtrl', ParentNewEntrustCtrl);

    function ParentNewEntrustCtrl($scope,$state,EntrustModel,AppUtils,store,$stateParams) {
        $scope.$on('$ionicView.beforeEnter', function (event, viewData) {
            viewData.enableBack = true;
        });
        var vm = this;
        vm.entrust = {};
        var loginAccount = store.get("loginAccount");
        //vm.entrust.entrustId = loginAccount.memberId;
        //vm.entrust.toEntrustChildId = loginAccount.studnetId;

        vm.entrust.entrustId = 'A83FA905F6044E9CA30C52FDCD351794';
        vm.entrust.toEntrustChildId = '041DFD58D85D31A478B881F1EBE4ECA9';

        $scope.saveEntrust = function(){
            if(AppUtils.isUndefinedOrNull(vm.entrust.entrustContent)){
                AppUtils.showAlert("请输入留言内容！");
            }else{
                EntrustModel.saveEntrust(vm.entrust).$promise.then(function(response){
                    var result = response.result;
                    if(response.stat == 'success'){
                        AppUtils.showAlert("提交成功！");
                        AppUtils.goBack();
                        //$state.go("memberMenu.parentEntrustList");
                    }else{
                        AppUtils.showAlert("提交失败！");
                    }
                })
            }
        }


    }

})();
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    TeacherEntrustCtrl.$inject = ["$scope", "$state", "EntrustModel", "AppUtils", "store"];
    angular.module('App.pages.member')
        .controller('TeacherEntrustCtrl', TeacherEntrustCtrl);


    function TeacherEntrustCtrl($scope,$state,EntrustModel,AppUtils,store) {

        $scope.$on('$ionicView.beforeEnter', function (event, viewData) {
            viewData.enableBack = true;
        });

        $scope.gotoDetail = function(entrustId){
            if(!AppUtils.isUndefinedOrNull(entrustId)){
                $state.go("memberMenu.teacherEntrustInfo",{entrustId:entrustId});
            }else{
                AppUtils.showAlert("请选择要查看的嘱托！");
            }
        }

        var vm = this;
        vm.unsolvedExhortaions = [];
        vm.solvedExhortaions = [];
        vm.unsolvedPageIndex = 1;
        vm.solvedPageIndex = 0;
        vm.exhortaions = [];
        vm.loadUnsolvedExhortaionsFlag = 'loading';//neverLoad|loadFinish|loading
        vm.loadSolvedExhortaionsFlag = 'neverLoad';
        vm.loadMoreBtnStatus = true;
        vm.loadMoreBtnStr = "加载更多";
        vm.entrustStatusParams = 'unexecuted';//unexecuted待办嘱托状态,executed为已办嘱托状态
        vm.sortType = 'entrustTime';
        vm.pageIndex = 1;//第一页
        var loginAccount = store.get("loginAccount");

        //切换不同嘱托状态列表
        $scope.changeStatus = function(status) {
            if($scope.isUnsolved != status){
                if(status == true){
                    vm.exhortaions = _.clone(vm.unsolvedExhortaions);
                    vm.isUnsolved = true;
                    vm.entrustTitle = "待办列表";
                    vm.entrustStatusParams = 'unexecuted';
                    vm.sortType = 'entrustTime';
                    if(vm.loadUnsolvedExhortaionsFlag == 'neverLoad'){
                        vm.pageIndex = 1;//第一页
                        vm.getEntrustPage();
                    }else if(vm.loadUnsolvedExhortaionsFlag == 'loading'){
                        vm.loadMoreBtnStatus = true;
                        vm.loadMoreBtnStr = "加载更多";
                    }else if(vm.loadUnsolvedExhortaionsFlag == 'loadFinish'){
                        vm.loadMoreBtnStatus = false;
                        vm.loadMoreBtnStr = "没有更多数据了";
                    }
                }else if(status == false){
                    vm.exhortaions = _.clone(vm.solvedExhortaions);
                    vm.isUnsolved = false;
                    vm.entrustTitle = "已办列表";
                    vm.entrustStatusParams = 'execute';
                    vm.sortType = 'executeTime';
                    if(vm.loadSolvedExhortaionsFlag == 'neverLoad'){
                        vm.pageIndex = 1;//第一页
                        vm.getEntrustPage();
                    }else if(vm.loadSolvedExhortaionsFlag == 'loading'){
                        vm.loadMoreBtnStatus = true;
                        vm.loadMoreBtnStr = "加载更多";
                    }else if(vm.loadSolvedExhortaionsFlag == 'loadFinish'){
                        vm.loadMoreBtnStatus = false;
                        vm.loadMoreBtnStr = "没有更多数据了";
                    }
                }
                AppUtils.scrollTop();
            }
        }

        $scope.loadMoreEntrust = function(){
            if(vm.loadMoreBtnStatus){
                if(vm.entrustStatusParams == 'unexecuted'){
                    vm.pageIndex = vm.unsolvedPageIndex + 1;
                }else if(vm.entrustStatusParams == 'execute'){
                    vm.pageIndex = vm.solvedPageIndex + 1;
                }
                vm.getEntrustPage();
            }
        }


        vm.getEntrustPage = function(){
            EntrustModel.getEntrustPage({
                entrustState: vm.entrustStatusParams,
                toEntrustId: loginAccount.memberId,
                //toEntrustId: '81B9970E608FA971E6A3615C78F98C6A',
                sortType: vm.sortType,
                pageInfo: {
                    pageSize: 5,
                    pageNumber: vm.pageIndex
                }
            }).$promise.then(function(response){
                if(response.stat == 'err'){
                    AppUtils.showAlert(response.msg);
                }else{
                    var reponseDate = response.pageResult;
                    var items = reponseDate.pageResult;
                    var pageIndex = reponseDate.pageIndex;
                    var pageTotalPageSize = reponseDate.pageTotalPageSize;
                    if(pageIndex == pageTotalPageSize || items.length == 0){
                        vm.loadMoreBtnStatus = false;
                        vm.loadMoreBtnStr = "没有更多数据了";
                        if(vm.entrustStatusParams == 'unexecuted'){
                            vm.loadUnsolvedExhortaionsFlag = 'loadFinish';//不再加载待办嘱托列表数据
                        }else if(vm.entrustStatusParams == 'execute'){
                            vm.loadSolvedExhortaionsFlag = 'loadFinish';//不再加载已办嘱托列表数据
                        }
                    }
                    if(vm.entrustStatusParams == 'unexecuted'){
                        vm.unsolvedPageIndex = pageIndex;
                        angular.forEach(items,function(data,index,array){
                            vm.unsolvedExhortaions.push(data);
                        })
                        vm.exhortaions = _.clone(vm.unsolvedExhortaions);
                    }else{
                        if(vm.loadSolvedExhortaionsFlag != 'loadFinish'){
                            vm.loadSolvedExhortaionsFlag = 'loading';
                        }
                        vm.solvedPageIndex = pageIndex;
                        angular.forEach(items,function(data,index,array){
                            vm.solvedExhortaions.push(data);
                        })
                        vm.exhortaions = _.clone(vm.solvedExhortaions);
                    }
                }
            })
        }

        vm.entrustTitle = "嘱托列表";
        vm.isUnsolved = true;
        vm.getEntrustPage();
    }

})();

/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    TeacherEntrustInfoCtrl.$inject = ["entrustId", "$scope", "$state", "EntrustModel", "AppUtils"];
    angular.module('App.pages.member')
        .controller('TeacherEntrustInfoCtrl', TeacherEntrustInfoCtrl);

    function TeacherEntrustInfoCtrl(entrustId,$scope,$state,EntrustModel,AppUtils) {
        $scope.$on('$ionicView.beforeEnter', function (event, viewData) {
            viewData.enableBack = true;
        });





        var vm = this;
        vm.init = function(){
            if(!AppUtils.isUndefinedOrNull(entrustId)){
                EntrustModel.getEntrustInfo({entrustId: entrustId}).$promise.then(function(response){
                    if(response.stat == 'err'){
                        AppUtils.showAlert(response.msg);
                    }else{
                        vm.entrust = response.entrust;
                    }
                })
            }else{
                AppUtils.showAlert("未找到该嘱托！");
                $state.go("classMenu.entrust",entrustId);
            }
        }
        vm.init();


        $scope.executeEntrust = function(){
            if(!AppUtils.isUndefinedOrNull(vm.entrust.id)){
                EntrustModel.executedEntrust({entrustId:vm.entrust.id}).$promise.then(function(response){
                    if(response.stat == 'err'){
                        AppUtils.showAlert("执行失败：" + response.msg);
                    }else if(response.stat == 'success'){
                        AppUtils.showAlert("成功修改嘱托状态！");
                        vm.init();
                    }
                })
            }
        }
    }

})();
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    MsgCtrl.$inject = ["$scope", "$state", "$stateParams", "AppUtils", "MsgModel", "$ionicPopup"];
    angular.module('App.pages.member')
        .controller('MsgCtrl', MsgCtrl);

    function MsgCtrl($scope,$state,$stateParams,AppUtils,MsgModel,$ionicPopup) {

        var vm = this;
        vm.disableSubmitBtn = false;
        vm.msgInfo = {};


        //var loginAccount = store.get("loginAccount");
        //loginAccount.memberId;

        vm.msgInfo.memberId = "";
        vm.msgInfo.toMemberId = $stateParams.toMemberId;

        $scope.$on('$ionicView.beforeEnter', function (event, viewData) {
            viewData.enableBack = true;
        });

        if(AppUtils.isUndefinedOrNull($stateParams.toMemberId)){
            AppUtils.showAlert("留言必要参数为空！");
            $state.go("memberMenu.parentInfo");
            vm.disableSubmitBtn = true;
        }

        $scope.saveMsgInfo = function(){
            if(AppUtils.isUndefinedOrNull(vm.msgInfo.msgContent)){
                AppUtils.showAlert("请输入留言内容！");
                return false;
            }
            MsgModel.createNewMsg(vm.msgInfo).$promise.then(function(response){
                var result = response.result;
                if(!AppUtils.isUndefinedOrNull(result) && result == 'success'){
                    AppUtils.showAlert("留言成功！");
                    AppUtils.goBack();
                }
            })
        }
    }
})();

/**
 * Created by hxpeng on 2017/3/24.
 */

(function () {
    'use strict';

    MsgModel.$inject = ["API", "$resource"];
    angular.module('App.pages.member')
        .service('MsgModel', MsgModel);

    function MsgModel(API,$resource) {
        this.actions = {}
        this.actions.createNewMsg = {
            method: 'POST',
            url: API + '/msg/createNewMsg'
        }

        this.actions.findMsgPage = {
            method: 'POST',
            url: API + '/msg/findMsgPageInfo'
        }
        return $resource.call(this, this.url, this.params, this.actions)
    }
})();
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    ParentCtrl.$inject = ["$scope", "store", "$state", "$ionicSlideBoxDelegate", "AppUtils", "MsgModel"];
    angular.module('App.pages.member')
        .controller('ParentCtrl', ParentCtrl);

    function ParentCtrl($scope,store,$state,$ionicSlideBoxDelegate,AppUtils,MsgModel) {

        var vm = this;
        $scope.next = function() {
            $ionicSlideBoxDelegate.next();
        };
        $scope.previous = function() {
            $ionicSlideBoxDelegate.previous();
        };
        $scope.slideChanged = function(index) {
            $scope.slideIndex = index;
        };
        $ionicSlideBoxDelegate.loop(true); //解决轮播至最后一个不轮播的问题

        var vm = this;
        vm.items = [];
        vm.pageIndex = 1;
        vm.loadMoreBtnStatus = true;
        vm.loadMoreBtnStr = "加载更多";

        $scope.loadMoreEntrust = function(){
            if(vm.loadMoreBtnStatus){
                vm.pageIndex = vm.pageIndex + 1;
                vm.getMsgPage();
            }
        }

        var loginAccount = store.get("loginAccount");
        $scope.memberId;
        $scope.memberId = loginAccount.memberId;
        $scope.studentId = loginAccount.studentId;
        //$scope.memberId = 'A83FA905F6044E9CA30C52FDCD351794';

        vm.getMsgPage = function(){
            MsgModel.findMsgPage({
                toMemberId: $scope.memberId,
                pageInfo: {
                    pageSize: 10,
                    pageNumber: vm.pageIndex
                }
            }).$promise.then(function(response){
                if(response.stat == 'err'){
                    AppUtils.showAlert(response.msg);
                }else{
                    var reponseDate = response.pageResult;
                    var items = reponseDate.pageResult;
                    var pageIndex = reponseDate.pageIndex;
                    var pageTotalPageSize = reponseDate.pageTotalPageSize;
                    if(pageIndex == pageTotalPageSize || items.length == 0){
                        vm.loadMoreBtnStatus = false;
                        vm.loadMoreBtnStr = "没有更多数据了";
                    }
                    angular.forEach(items,function(data){
                        vm.items.push(data);
                    })
                }
            })
        }
        vm.getMsgPage();
    }
})();
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    ParentInfoCtrl.$inject = ["studentId", "$scope", "AppUtils", "MemberModel", "$ionicPopup", "$window", "store", "Global"];
    angular.module('App.pages.member')
        .controller('ParentInfoCtrl', ParentInfoCtrl);

    function ParentInfoCtrl(studentId,$scope,AppUtils,MemberModel,$ionicPopup,$window,store,Global) {
        $scope.$on('$ionicView.beforeEnter', function (event, viewData) {
            viewData.enableBack = true;
        });

        $scope.studentId = studentId;

        var vm = this;
        vm.memberInfoNotChange = true;
        vm.memberEdit = false;
        vm.disableLeavenMsgBtn = false;
        vm.memberInfo = {};

        $scope.change = function(){
            vm.memberInfoIsChange = false;
        }

        vm.loginAccount = store.get("loginAccount");
        vm.showLeaveMsgBtn = false;
        if(!AppUtils.isUndefinedOrNull(vm.loginAccount)){
            if(vm.loginAccount.memberType == '1'){
                vm.showLeaveMsgBtn = true;
            }
        }



        $scope.goBack = function(){
            if(vm.memberEdit == true){
                var confirmPopup = $ionicPopup.confirm({
                    title: "提示",
                    template: "是否退出家长信息修改？",
                    buttons: [
                        {
                            text: '是',
                            onTap: function() {
                                vm.memberEdit = false;
                            }
                        },
                        {
                            text: '<b>否</b>',
                            type: 'button-positive',
                            onTap: function() {
                                vm.memberEdit = true;
                            }
                        }
                    ]
                });
            }else{
                $window.history.go(-1);
            }
        }


        $scope.editMemberInfo = function(){
            if(vm.memberEdit == true){
                var confirmPopup = $ionicPopup.confirm({
                    title: "提示",
                    template: "是否退出家长信息修改？",
                    buttons: [
                        {
                            text: '是',
                            onTap: function() {
                                vm.memberEdit = false;
                            }
                        },
                        {
                            text: '<b>否</b>',
                            type: 'button-positive',
                            onTap: function() {
                                vm.memberEdit = true;
                            }
                        }
                    ]
                });
            }else{
                vm.memberEdit = true;
            }
        }

        //parentId = "A83FA905F6044E9CA30C52FDCD351794";
        var memberType = "2";

        $scope.studentInfo = {};
        $scope.fatherInfo = {};
        $scope.motherInfo = {};

        vm.init = function(){
            if(!AppUtils.isUndefinedOrNull(studentId)){
                MemberModel.getParentInfo({id: studentId}).$promise.then(function(response){
                    if(response.stat == 'err'){
                        AppUtils.showAlert(response.msg);
                    }else{
                        if(AppUtils.isUndefinedOrNull(response.memberList)){
                            AppUtils.showAlert("未找到此家长信息");
                            AppUtils.goBack();
                        }else{
                            angular.forEach(response.memberList,function(obj){
                                if(obj.memberType == '3'){
                                    $scope.studentInfo = obj;
                                    if(AppUtils.isUndefinedOrNull(obj.avatarPath)){
                                        $scope.studentInfo.avatarPath = Global.default_avatarPath;
                                    }
                                }else if(obj.memberType == '2'){
                                    if(obj.memberRelType == 'father'){
                                        $scope.fatherInfo = obj;
                                    }else if(obj.memberRelType == 'mother'){
                                        $scope.motherInfo = obj;

                                    }
                                }
                                console.log(obj);
                            })
                        }
                    }
                })
            }else{
                AppUtils.showAlert("未找到家长信息！");
            }
        }
        vm.init();
        $scope.submit = function() {
            if(AppUtils.isUndefinedOrNull(vm.memberInfo.memberName)){
                AppUtils.showAlert("请输入家长姓名！");
                return false;
            }
            if(AppUtils.isUndefinedOrNull(vm.memberInfo.memberPhone)){
                AppUtils.showAlert("请输入家长手机号码！");
                return false;
            }
            if(AppUtils.isUndefinedOrNull(vm.memberInfo.memberAddress)){
                AppUtils.showAlert("请输入家长居住地址！");
                return false;
            }

            MemberModel.saveParentMemberInfo(vm.memberInfo).$promise.then(function(response){
                var result = response.result;
                if(!AppUtils.isUndefinedOrNull(result) && result == 'success'){
                    AppUtils.showAlert("保存家长信息成功！");
                    vm.memberEdit = false;
                }else{
                    AppUtils.showAlert("保存失败！");
                }

            })
        };
    }
})();

/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    StudentCtrl.$inject = ["studentId", "$scope", "$state", "AppUtils", "MemberModel"];
    angular.module('App.pages.member')
        .controller('StudentCtrl', StudentCtrl);

    function StudentCtrl(studentId,$scope,$state,AppUtils,MemberModel) {

        $scope.$on('$ionicView.beforeEnter', function (event, viewData) {
            viewData.enableBack = true;
        });

        var vm = this;
        vm.parentId = '';

        var objParams = {};
        //objParams.memberId = '041DFD58D85D31A478B881F1EBE4ECA9';
        //objParams.relType = 'father';
        objParams.memberId = studentId;
        objParams.relType = 'father';
        MemberModel.getParentId(objParams).$promise.then(function(response){
            if(response.stat == 'err'){
                AppUtils.showAlert(response.msg);
                AppUtils.goBack();
            }else if(response.stat == 'success'){
                vm.parentId = response.parentId;
            }
        })
    }
})();
/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    TeacherCtrl.$inject = ["$scope", "$ionicSlideBoxDelegate", "MemberModel"];
    angular.module('App.pages.member')
        .controller('TeacherCtrl', TeacherCtrl);

    function TeacherCtrl($scope,$ionicSlideBoxDelegate,MemberModel) {
        $scope.next = function() {
            $ionicSlideBoxDelegate.next();
        };
        $scope.previous = function() {
            $ionicSlideBoxDelegate.previous();
        };
        $scope.slideChanged = function(index) {
            $scope.slideIndex = index;
        };

        $ionicSlideBoxDelegate.loop(true); //解决轮播至最后一个不轮播的问题

        var vm = this;
        vm.items = [];
        vm.pageIndex = 1;
        vm.loadMoreBtnStatus = true;
        vm.loadMoreBtnStr = "加载更多";

        $scope.loadMoreEntrust = function(){
            if(vm.loadMoreBtnStatus){
                vm.pageIndex = vm.pageIndex + 1;
                vm.getStudentPage();
            }
        }
        var id = '16BFD02EB985735E351C6B89A19CA3EE';
        vm.getStudentPage = function(){
            MemberModel.getStudentList({
                classId: id,
                pageInfo: {
                    pageSize: 10,
                    pageNumber: vm.pageIndex
                }
            }).$promise.then(function(response){
                if(response.stat == 'err'){
                    AppUtils.showAlert(response.msg);
                }else{
                    var reponseDate = response.pageResult;
                    var items = reponseDate.pageResult;
                    var pageIndex = reponseDate.pageIndex;
                    var pageTotalPageSize = reponseDate.pageTotalPageSize;
                    if(pageIndex == pageTotalPageSize || items.length == 0){
                        vm.loadMoreBtnStatus = false;
                        vm.loadMoreBtnStr = "没有更多数据了";
                    }
                    angular.forEach(items,function(data){
                        vm.items.push(data);
                    })
                }
            })
        }
        vm.getStudentPage();
    }
})();

/**
 * Created by dzd on 2017/3/28.
 */
(function () {
    'use strict';

    DisplayCtrl.$inject = ["$scope", "$state", "MemberModel", "$location", "$http", "Global", "$filter", "store"];
    angular.module('App.pages.class')
        .controller('DisplayCtrl', DisplayCtrl);

    function DisplayCtrl($scope,$state,MemberModel,$location,$http,Global,$filter,store) {
        var currentPath = $location.url();
        if(currentPath.indexOf("#") != -1){
            currentPath = currentPath.split('#')[0];
        }
        currentPath = Global.path.wechat_path + currentPath;
        $http.post(Global.path.server_sdk_auth_path,{"url":currentPath})
            .success(function(data){
                wx.config({
                    debug: false,
                    appId: data.appId,
                    timestamp: data.timestamp,
                    nonceStr: data.noncestr,
                    signature: data.signature,
                    jsApiList: ['chooseImage','previewImage']
                });
                wx.error(function(res){
                    console.log(res);

                });
            })
            .error(function(data,header,config,status){
                alert("请求微信sdk校验异常");
            });


        $scope.photo = function(){
            $state.go("memberMenu.upload");
        }
        var vm = this;
        vm.loginAccount = store.get('loginAccount');
        vm.exhortaions = [];
        vm.loadMoreBtnStatus = true;
        vm.loadMoreBtnStr = "加载更多";
        vm.pageIndex = 1;//第一页

        $scope.loadMoreActivity = function(){
            if(vm.loadMoreBtnStatus){
                vm.pageIndex = vm.pageIndex + 1;
                vm.init();
            }
        }

        //大图片预览
        $scope.previewImg = function(url,key){
            var imgArray = [];
            angular.forEach($scope.resultArray, function(data) {
                if(data.key == key){
                    angular.forEach(data.timeArray, function(val) {
                        imgArray.push(val.url);
                    });
                }
            });
            wx.previewImage({
                current: url,
                urls: imgArray
            });
        }
        vm.init = function(){
            MemberModel.queryClassPhoto({
                //classId: '16BFD02EB985735E351C6B89A19CA3EE',
                classId: vm.loginAccount.classId,
                pageInfo: {
                    pageSize: 5,
                    pageNumber: vm.pageIndex
                }
            }).$promise.then(function(response){
                var reponseDate = response.classPhoto;
                var items = reponseDate.pageResult;
                var pageIndex = reponseDate.pageIndex;
                var pageTotalPageSize = reponseDate.pageTotalPageSize;
                if(pageIndex == pageTotalPageSize || items.length == 0){
                    vm.loadMoreBtnStatus = false;
                    vm.loadMoreBtnStr = "没有更多数据了";
                }

                $scope.resultArray = [];
                var repeat = [];
                angular.forEach (items,function(data,index,array){
                    var keepRun = true;
                    var key = $filter("date")(new Date(data.createDate), "yyyy-MM-dd");
                    angular.forEach(repeat,function(i){
                        if(key == i){
                            keepRun = false;
                        }
                    });

                    if(keepRun){
                        var obj = {};
                        obj.key = key;
                        var timeArray = [];
                        angular.forEach (items,function(objecy,k){
                            var time = $filter("date")(new Date(objecy.createDate), "yyyy-MM-dd");
                            if(key == time){
                                var imgObj = {};
                                imgObj.url = objecy.filePath;
                                imgObj.key = key;
                                timeArray.push(imgObj);
                            }
                        })
                        obj.timeArray = timeArray;
                        $scope.resultArray.push(obj);
                        repeat.push(key);
                    }
                })
            })
        }
        vm.init();
    }
})();

/**
 * Created by dzd on 2017/3/28.
 */
(function () {
    'use strict';

    UploadCtrl.$inject = ["$scope", "AppUtils", "$location", "$http", "Global", "MemberModel", "$state"];
    angular.module('App.pages.member')
        .controller('UploadCtrl', UploadCtrl);

    function UploadCtrl($scope,AppUtils,$location,$http,Global,MemberModel,$state) {
        var currentPath = $location.url();
        if(currentPath.indexOf("#") != -1){
            currentPath = currentPath.split('#')[0];
        }
        currentPath = Global.path.wechat_path + currentPath;
        $http.post(Global.path.server_sdk_auth_path,{"url":currentPath})
            .success(function(data){
                wx.config({
                    debug: false,
                    appId: data.appId,
                    timestamp: data.timestamp,
                    nonceStr: data.noncestr,
                    signature: data.signature,
                    jsApiList: ['scanQRCode','chooseImage','previewImage','uploadImage']
                });
                wx.error(function(res){
                    console.log(res);

                });
            })
            .error(function(data,header,config,status){
                alert("请求微信sdk校验异常");
            });


        var vm = this;
        vm.imgIndex = 0;//imgUrl中保存的图片唯一标识符
        vm.imgUrl = [];//页面预览图片数组
        vm.postImgArray = [];//提交后台图片serverId数组
        $scope.localIds = "";
        $scope.chooseImg = function(){
            wx.chooseImage({
                count: 9,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success: function (res) {
                    var localIds = res.localIds;
                    syncPutImg(localIds);
                    AppUtils.loading();
                }
            });
        }

        //同步上传图片
        var syncPutImg = function(localIds){
            var img = localIds.pop();
            wx.uploadImage({
                localId: img,
                isShowProgressTips: 0,
                success: function (res) {
                    var serverId = res.serverId; // 返回图片的服务器端ID
                    var obj = {};
                    obj.imgIndex = vm.imgIndex;
                    obj.url = img;
                    obj.serverId = serverId;
                    $scope.$apply(function(){
                        vm.imgUrl.push(obj);
                    });
                    vm.imgIndex++;
                    if(localIds.length > 0){
                        syncPutImg(localIds);
                    }else{
                        AppUtils.loadfinish();
                    }
                }
            });
        };

        //大图片预览
        $scope.previewImg = function(url){
            var imgArray = [];
            angular.forEach(vm.imgUrl, function(obj, index) {
                imgArray.push(obj.url);
            });
            wx.previewImage({
                current: url,
                urls: imgArray
            });
        }

        //删除选择的图片
        $scope.removePicture = function(url,imgIndex){
            var urlIndex = null;
            angular.forEach(vm.imgUrl, function(obj, index) {
                if (obj.url === url && obj.imgIndex === imgIndex) {
                    urlIndex = index;
                }
            });
            $scope.$apply(function(){
                vm.imgUrl.splice(urlIndex, 1);
            });
        }


        $scope.uploadImg = function(){
            if(!AppUtils.isUndefinedOrNull(vm.imgUrl)){
                angular.forEach(vm.imgUrl, function(obj, index) {
                    if (!AppUtils.isUndefinedOrNull(obj.serverId)) {
                        vm.postImgArray.push(obj.serverId);
                    }
                });
            }
            MemberModel.submitUploadImg({serverIds: JSON.stringify(vm.postImgArray)}).$promise.then(function(response){
                if(response.stat == 'success'){
                    AppUtils.showAlert("提交成功！");
                    $state.go("memberMenu.display");
                }else if(response.stat == 'err'){
                    AppUtils.showAlert("提交失败:" + response.msg);
                }
            });
        }

    }

})();